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

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

问题描述

在我的应用程序,我有一类为UI的工作人员,它的名称是SettingActivity。

然后做一些工作在后台,我结合这个UI类(SettingActivity)到服务。 有两个在该服务(在.aidl文件中定义)predefined方法,一种是startTask(),另一种是stopTask()。

在startTask(),我打了一个电话给AsyncTask的。但是,当我检查这个的AsyncTask的活套的名称。它是主。在我看来,的AsyncTask的应该启动另一个线程比主线程其他

因此​​,没有人知道为什么会这样?

的codeS如下:

 @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        Log.d(。在preExecute的标签,+ Looper.myLooper()getThread()的getName());
    }
 

然后,我会作为主要的输出。

解决方案

这是AsyncTask的有几个部分组成: doInBackground 方法呢,其实,在一个单独的线程上运行和 onPostExecute 方法,该方法在UI线程上运行。 onPostExecute 的目的是公布结果(例如更新视图层次结构,或者在文本视图中设置文本),必须在UI线程中完成的。它也可以发布最新进展。为了让这一切工作正常,AsyncTask的必须创建和执行方法调用,在UI线程上。

。这样做会引起程序崩溃

-

您不能在 doInBackground 调用从UI操作

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

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().

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?

The codes are as follows:

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

Then I will get main as the output.

解决方案

An AsyncTask has several parts: a doInBackground method that does, in fact, run on a separate thread, and a onPostExecute method that runs on the UI thread. 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.

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

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

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