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 AsyncTask
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.
Asked
Active
Viewed 1,743 times
1

Egor
- 39,695
- 10
- 113
- 130
2 Answers
1
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.

N-JOY
- 10,344
- 7
- 51
- 69
-
Another problem is that my game contains two activities: main activity and a game activity. I'm starting my game activity via startActivity(), and then it starts its separate thread. Now the first activity is not accessible from the game activity, so I can't access a handler created there. What should I do? – Egor Jun 09 '11 at 08:19
-
create a static instance of your main activity. say public static MainActivity mainactivity; oncreate(){ mainactivity =this; } now use this instance.getHandler().sendEmptyMessage(0); – N-JOY Jun 09 '11 at 10:53
1
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.

Alex Gitelman
- 24,429
- 7
- 52
- 49