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: エラー/AndroidRuntime(1433): java.lang.RuntimeException: Looper.prepare() を呼び出していないスレッド内でハンドラを作成できません

4

1 に答える 1

0

問題はToast.makeText(this, "TimerMethod Running "+number, Toast.LENGTH_SHORT).show();TimerMethod 関数にあると思います-ワーカースレッドからUIに関連する関数を呼び出すことはできません。UI スレッドで実行される部分に既に Toast があるのに、TimerMethod にもう 1 つあるのはなぜでしょうか?

デバッグには、Toast の代わりにできるだけ Log を使用することをお勧めします。

于 2010-09-06T16:39:16.230 に答える