0

I have a code like this:

final Context context = this;
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    @Override
    public void run()
    {
        new CheckMessageTask(context).execute(); //ERROR
    }
}, 2500, 10 * 60 * 1000); //Every 10 Minutes

The Timer should execute CheckMessageTask every 10 minutes. The problem is that this error appears:

E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    java.lang.ExceptionInInitializerError
    at -package-CheckMessageService$1.run(CheckMessageService.java:138)
    at java.util.Timer$TimerImpl.run(Timer.java:284)
    Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
    at android.os.Handler.<init>(Handler.java:121)
    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
    at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
    at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
    ... 2 more

CheckMessageTask extends Asynctask and doesn't run UI code, so that is not the reason. The code works fine on Android Jelly Bean 4.1.2, but not on Android Gingerbread. How can I fix it?

4

2 に答える 2

2

タイマー タスクは別のスレッドで実行されます。メインUIスレッドにasynctaskをロードする必要があります

以下のスレッド ルールのトピックの下のリンクを確認してください。

http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTaskクラスは にロードする必要がありますUI thread。これは の時点で自動的に行われますJELLY_BEAN

したがって、ジェリービーンでは正常に機能します。

于 2013-06-11T17:10:21.220 に答える