的AsyncTask实例关闭UI线程
问题描述:
报价从here得到的文档的AsyncTask,它说的AsyncTask实例关闭UI线程
- 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.
现在什么是创建在UI线程的AsyncTask参考的原因是什么?这是Looper的问题吗?
答
我认为这将是毫无意义在其他地方创造的AsyncTask因为的AsyncTask是专门用来做UI线程上的一些准备工作,然后做一些事情在另一个线程然后再张贴在UI线程任何结果。
答
我认为这样做是为了确保Handler在UI线程上初始化,因此在处理程序的构造函数中,myLooper()将返回mainUIThreadLooper,稍后将发送的消息将转入UI线程。
public abstract class AsyncTask<Params, Progress, Result> {
private static final InternalHandler sHandler = new InternalHandler();
....
}
和
public Handler() {
...
mLooper = Looper.myLooper();
...
}
答
请检查this答案。
的AsyncTask.class必须在UI线程加载,因为它有静态田间引用处理程序:
private static final InternalHandler sHandler = new InternalHandler();
所以,如果你将与弯另一个线程运行AsynckTask的第一次( NonMainThred)然后任何实例上AsuncTask将发布它的onPostExecute(及其他)方法,以特定NonMainThread没有梅特在那里你会试图启动您的AsyncTask从。
如果现在你试图解决从onPostExecute任何Android的UI元素将出现以下错误崩溃:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.