1

Quoting the AsyncTask documentation gotten from here, it says

  • The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
  • The task instance must be created on the UI thread.
  • execute(Params...) must be invoked on the UI thread.
  • Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.

Now what is the reason for creating the AsyncTask reference on the UI Thread ? Is it the problem with the Looper ?

Rajesh
  • 15,724
  • 7
  • 46
  • 95
user1730789
  • 5,157
  • 8
  • 36
  • 57

3 Answers3

2

I think to do so is to make sure the Handler is initialized on the UI thread,so in the handler's constructor,myLooper() will return the mainUIThreadLooper,and messages to be sent later will diliver to the UI thread.

public abstract class AsyncTask<Params, Progress, Result> {
    private static final InternalHandler sHandler = new InternalHandler();
....
}

and

public Handler() {
   ...
   mLooper = Looper.myLooper();
   ...
}
nut
  • 375
  • 2
  • 13
1

I think it would be rather meaningless to create AsyncTask elsewhere because AsyncTask is made specifically to do some preparations on the UI thread then do something in another thread then post any results in the UI thread again.

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
0

Please, check this answer.

The AsyncTask.class must be loaded on UI thread because it has static fied referencing handler:

private static final InternalHandler sHandler = new InternalHandler();

So if you will run AsynckTask for the very first time on another thread with looper (NonMainThred) then ANY instances on AsuncTask will post it's onPostExecute (and others) methods to that particular NonMainThread no metter where you will try to launch your AsyncTask from.

If now you try to deal with any android-UI elements from that onPostExecute it will crash with the following error:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Community
  • 1
  • 1
vir us
  • 9,920
  • 6
  • 57
  • 66