Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

android - What is the difference between loading and creating AsyncTask on the UI thread?

While reading AsyncTask documentation, the part on Threading rules, I found this:

  • 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.

What is meant by "loading"? It's not instantiating or executing, as the documentation talked about those later.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't believe that this answer is actually correct.

It wouldn't make sense for the documentation to separately list instantiation and loading, if those things were actually the same. I believe this statement

The AsyncTask class must be loaded on the UI thread.

is referring to Java Class Loading. In other words, the AsyncTask class itself needs to be loaded on the main thread. In Jelly Bean (or later), this is automatic. But, in older versions of Android, there is the potential for this class to be loaded on another thread, which can cause problems.

See this Google discussion for more information. Basically, there are conditions (for example, code using IntentService) that can cause the AsyncTask to be first loaded on the wrong (non-main) thread.

The simplest fix for this, prior to Jelly Bean, seems to be to use something like:

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

in the Application's onCreate() method, to force class loading to happen when you want it to.


Creating the AsyncTask instance is probably what you think it is ... instantiating it:

MyAsyncTask task = new MyAsyncTask();

and that should also be run on the main thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...