Вопрос

Lately, I've encountered more and more errors that may seem easy to someone with more experience, but are quite hard for me to figure out.

I'm trying to create a background service that checks for new feed entries each X minutes. Hence, I'm starting a loop from a service, and that loop creates an asynctask.

It works like a charm on my 4.1 phone, but on my 2.3 emulator it gives the following force close:

09-11 19:53:35.905: E/AndroidRuntime(354): FATAL EXCEPTION: AppConstructorPushLoop
09-11 19:53:35.905: E/AndroidRuntime(354): java.lang.ExceptionInInitializerError
09-11 19:53:35.905: E/AndroidRuntime(354):  at com.appconstructor.actest.PushNotificationService$1.run(PushNotificationService.java:54)
09-11 19:53:35.905: E/AndroidRuntime(354):  at java.util.Timer$TimerImpl.run(Timer.java:284)
09-11 19:53:35.905: E/AndroidRuntime(354): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
09-11 19:53:35.905: E/AndroidRuntime(354):  at android.os.Handler.<init>(Handler.java:121)
09-11 19:53:35.905: E/AndroidRuntime(354):  at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
09-11 19:53:35.905: E/AndroidRuntime(354):  at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
09-11 19:53:35.905: E/AndroidRuntime(354):  at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
09-11 19:53:35.905: E/AndroidRuntime(354):  ... 2 more

I realize this usually means I'm trying to do UI stuff in a non-UI thread, but this is not the case. In fact, even if I comment out ALL activity in the ASyncTask, it still forces close. It only stops force closing when I comment out the line starting the loop

This only happens on my 2.3 emulator, and is unrelated to the 4.0 style notification I'm using.

Would anyone know more about this?

Thanks!

edit -> If I call Looper.prepare() I get the error that that may happen only once per thread.

Это было полезно?

Решение

you are updating the UI tread from the timer , if you simply put even a toast inside the timer it wont work because timer is not attach with UI thread and you can't prepare the thread two times cause when you call thread.execute it already prepare and in 4.1 its handling by android OS itself. AsyncTask can only call from UI thread.

new refreshList().execute();

run your this code inside runOnUiThread(action) and dont forget to cancel the Thread before executing a new one.

Другие советы

Please start your AsyncTask from http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable) method. And with Service - create new Handler() instance on UI thread and start your AsyncTask on http://developer.android.com/reference/android/os/Handler.html#post(java.lang.Runnable)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top