开发者

Calling asynctask from runnable

开发者 https://www.devze.com 2023-03-05 23:00 出处:网络
Is it possible to execute an AsyncTask from Runnable? in my experience it can be done, but not safely. When my app first runs my AsyncTask runs fine from the Runnable. But when the app is moved to the

Is it possible to execute an AsyncTask from Runnable? in my experience it can be done, but not safely. When my app first runs my AsyncTask runs fine from the Runnable. But when the app is moved to the background, then brought back forward I get "Can't create handler inside thread that has not called Looper.prepare()".

Here's what I'm trying to do: I'm开发者_JAVA技巧 using MapView and invoking runOnFirstFix(Runnable) within onCreate. My Runnable calls an AsyncTask to perform a web service call which returns some data based on the location. I move the app to the background (by tapping the home button), after some time I bring my app forward again and I'm getting the exception at the point where I'm invoking execute() on my AsyncTask.

First of all, why is runOnFirstFix being executed again? Secondly, why is it causing the exception the second time around? I'm guessing that there is some part of the lifecycle that I don't understand.

Thanks.


It wasn't initially obvious to me that the AsyncTask needed to be called from the UI thread. So when runOnFirstFix ran the second time it was from withing a Runnable which wasn't on the UI thread. To solve the problem I simple created another Runnable inside the first to run the AsynchTask.

And the reason my runOnFirstFix seemed to be called twice was simply because I was creating a new instance of it.

0

精彩评论

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