为什么 AsyncTask 运行在应用程序的主线程中? [英] Why does AsyncTask run in the main Thread of an application?

查看:21
本文介绍了为什么 AsyncTask 运行在应用程序的主线程中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个用于 UI 内容的类,其名称是SettingActivity".

in my application, I have a class for UI stuff, the name of which is "SettingActivity".

然后为了在后台做一些工作,我将这个 UI 类(SettingActivity)绑定到一个服务.该Service中有两种预定义的方法(在.aidl文件中定义),一种是startTask(),另一种是stopTask().

Then for doing some jobs in background, I bind this UI class(SettingActivity) to a Service. There are two predefined methods in that Service(defined in .aidl file), one is startTask(), the other one is stopTask().

在 startTask() 中,我调用了一个 AsyncTask.但是当我检查这个 AsyncTask 的 Looper 的名字时.它是主要的".在我看来,一个 AsyncTask 应该启动一个不同于主线程的另一个线程.

Within startTask(), I made a call to an AsyncTask. But when I checked the name of the Looper of this AsyncTask. It is "main". In my opinion, an AsyncTask should start an another Thread other than the main Thread.

那么有人知道为什么会这样吗?

So does somebody know why this happens?

代码如下:<代码>

@Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d(TAG, "onPreExecute "+Looper.myLooper().getThread().getName());
    }

然后我会得到 main 作为输出.

Then I will get main as the output.

推荐答案

一个 AsyncTask 有几个你可以覆盖的部分:一个 doInBackground 方法,它实际上运行在一个单独的线程上,以及三种方法——onPreExecuteonProgressUpdateonPostExecute——在 UI 线程上运行.(这些方法的默认实现什么都不做,onProgressUpdate 只在你调用 publishProgress 时运行,通常是从 doInBackground 中调用.) onPostExecute 是发布必须在 UI 线程上完成的结果(例如更新视图层次结构,或在文本视图中设置文本).它还可以发布进度更新.为了让这一切正常工作,必须在 UI 线程上创建 AsyncTask,并调用 execute 方法.

An AsyncTask has several parts that you can override: a doInBackground method that does, in fact, run on a separate thread, and three methods—onPreExecute, onProgressUpdate, and onPostExecute—that run on the UI thread. (The default implementation of these methods do nothing and onProgressUpdate only runs if you call publishProgress, usually from within doInBackground.) The purpose of onPostExecute is to publish results (such as updating the view hierarchy, or setting text in a text view) that must be done on the UI thread. It also can post progress updates. In order for this to all work properly, the AsyncTask must be created, and the execute method called, on the UI thread.

您不得从 doInBackground 中调用 UI 操作——这样做会导致您的应用程序崩溃.

You must not call UI actions from within doInBackground -- doing so will crash your application.

这篇关于为什么 AsyncTask 运行在应用程序的主线程中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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