android timer handler
I 开发者_JS百科am using this code:
public class newtimer extends Activity {
private Timer myTimer;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
int number = 0;
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show();
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
Toast.makeText(getBaseContext(), "UI Thread Running "+number, Toast.LENGTH_SHORT).show();
}
};
}
When i run it i get this exception in logcat:
09-06 21:39:39.701: ERROR/AndroidRuntime(1433): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I would assume the problem is with the Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show();
in your TimerMethod function - you can't call any functions pertaining to the UI from worker threads. Since you already have a Toast in the portion that runs in the UI thread, why do you have another one in TimerMethod?
For debugging, I would recommend using Log as much as possible instead of Toast.
精彩评论