在 UI 线程上加载和创建 AsyncTask 有什么区别? [英] What is the difference between loading and creating AsyncTask on the UI thread?

查看:21
本文介绍了在 UI 线程上加载和创建 AsyncTask 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 AsyncTask 文档时,关于线程规则的部分,我发现这个:

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

  • 必须在 UI 线程上加载 AsyncTask 类.这个完成了自动从 JELLY_BEAN 开始.
  • 必须创建任务实例在 UI 线程上.
  • execute(Params...) 必须在 UI 线程上调用.

加载"是什么意思?它不是实例化或执行,因为文档稍后会谈到这些.

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

推荐答案

我不相信这个答案是实际上是正确的.

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

必须在 UI 线程上加载 AsyncTask 类.

The AsyncTask class must be loaded on the UI thread.

指的是 Java 类加载.换句话说,AsyncTask 本身需要加载到主线程上.在 Jelly Bean(或更高版本)中,这是自动的.但是,在旧版本的 Android 中,此类可能会加载到另一个线程上,这可能会导致问题.

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.

有关详细信息,请参阅此 Google 讨论.基本上,有一些条件(例如,使用 IntentService 的代码)会导致 AsyncTask 首先加载在错误的(非主) 线程.

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.

在 Jelly Bean 之前,最简单的解决方法似乎是使用类似的方法:

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

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

在应用程序的onCreate() 方法中, 强制在你想要的时候加载类.

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

创建AsyncTask 实例可能就是你认为的那样......实例化它:

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.

这篇关于在 UI 线程上加载和创建 AsyncTask 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆