开发者

None of my AsyncTasks get callbacks to onPostExecute

When I have a fresh install of my application, NONE of my AyncTasks seem to work. It doesn't matter which it is, they all fail with the message "sending message to a dead thread. " They're in all sorts of activities doing all sorts of different work, but they all fail.

If开发者_Python百科 I look at the threads in the thread viewer of DDMS, all 5 or so AsynchTask threads appear to be idle and waiting for work.

If I force close the application, and start it back up, they all start working.

They're all started on the UI thread.

Any ideas?


This is due to a bug in AsyncTask in the Android framework. AsyncTask.java has the following code:

private static final InternalHandler sHandler = new InternalHandler();

It expects this to be initialized on the main thread, but that is not guaranteed since it will be initialized on whichever thread happens to cause the class to run its static initializers. In your case, you're probably causing it to be initialized on the worker thread you created.

A simple workaround is to add the following code to the application's onCreate method:

Class.forName("android.os.AsyncTask");

This will force AsyncTask to be initialized in the main thread. I filed a bug on this in the android bug database. See http://code.google.com/p/android/issues/detail?id=20915.


Ok, so I've figured this one out, but if anyone has further explanation, that'd be great.

On application startup, I have some work that I want to do in the background - some downloading. I start a new HandlerThread and and I grab the looper from this handler thread and send it off to the Handler I create.

In handle message, for some operations when I think I'm done (error or finished), I wanted to make sure I cleaned up the looper, so I call getLooper().quit(). It turns out that the getLooper() call is returning the main threads looper. After I quit the looper, none of my AsynchTask tasks, even though they're getting passed back to the main threads Handler respond, because I've killed the looper.

I guess the next question would be why getLooper() is returning the main threads looper. Shouldn't it be using the one from the HandlerThread? Or is it that, because I created the HandlerThread on the UI thread, that it's somehow tied to the main thread?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜