timer = new Timer("Timer Thread");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
showDialog(0);
timeBar.setProgress(time);
}
}
}, INTERVAL, INTERVAL);`
My onCreateDialog method is working fine, so when I use showDialog(0) from a Button it works fine. But 开发者_如何学运维not if the method is called by a Scheduler.
Using a handler:
protected static final int DIALOG_OK= 0;
timer = new Timer("Timer Thread");
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
mDialogHandler.sendEmptyMessage(DIALOG_OK);
timeBar.setProgress(time);
}
}
}, INTERVAL, INTERVAL);
private Handler mDialogHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case DIALOG_OK:
// We are now back in the UI thread
showDialog(0);
}
};
};
This allows you to call method's on the UI thread from other threads. Need more explanation, just ask.
You need to call these methods on the UI thread.
One way to do this is via AsyncTask
, as in this answer.
Another way is to create a Handler and send messages to it from your TimerTask
.
You can read more about AsyncTasc
and the UI thread in Painless Threading.
精彩评论