I'm developing a game, that is running in a separate thread. Now I need to download an image from Internet. I've written an AsyncTask
class for that, but I can't figure out how to properly call it from my game thread? In fact, my AsyncTask
is blocking, though I need to wait before the image is downloaded. If I use runOnUIThread
, it does not block my thread and goes further, which doesn't fit me at all. I've tried also using Looper.prepare()
before running AsyncTask
, but this also does have some troubles: Looper.myLooper().quit()
does not seem to be working, and if I try to call the Asy开发者_运维知识库ncTask
once again, I get an exception telling me that I'm trying to call Looper.prepare()
for the second time.
How should I proceed? Thanks in advance.
If your background thread will block anyway, you don't need AsyncTask and can do image loading directly in this thread. To post on UI thread afterwards you will need to have Handler
with looper set up. One option is to pass a handler created in UI thread. Other option is to pass some context to your background thread and do
Handler h = new Handler(context.getMainLooper());
If you need some progress updates during image loading, you can use AsyncTask and use handler created as described.
if your game thread is not your main thread that is, if it is not UI thread then call handler from your game thread. now from this handler call your async task.
simply call something like this.
hm.sendEmptyMessage(0);
Handler hm = new Handler(){
public void handleMessage(Message msg)
{
//call async task.
}
};
Thanks.
精彩评论