0

我正在使用这段代码:

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();

        }
    };
}

当我运行它时,我在 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()

4

1 回答 1

0

我认为问题出Toast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show();在您的 TimerMethod 函数中 - 您不能从工作线程调用与 UI 有关的任何函数。既然在 UI 线程中运行的部分中已经有一个 Toast,为什么在 TimerMethod 中还有另一个?

对于调试,我建议尽可能使用 Log 而不是 Toast。

于 2010-09-06T16:39:16.230 回答