【问题标题】:android timer handler安卓定时器处理程序
【发布时间】:2010-09-06 16:15:13
【问题描述】:

我正在使用此代码:

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

【问题讨论】:

  • 该代码的格式完全错误。请在发布问题之前查看预览。

标签: android android-handler


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2017-02-02
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多