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

前端 未结 1 923
孤街浪徒
孤街浪徒 2020-12-11 10:12

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

  • The AsyncTask class must be loaded on the UI thread. This is
1条回答
  •  囚心锁ツ
    2020-12-11 10:35

    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.

    0 讨论(0)
提交回复
热议问题