异步任务 Android 示例

712

我在阅读有关 AsyncTask 的内容,然后我尝试了下面的简单程序。但它似乎不起作用。我该怎么做才能让它工作?

public class AsyncTaskActivity extends Activity {

    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

我只是想在后台进程中5秒后更改标签。

这是我的 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>

1
你可以通过在doInBackground()方法中调用publishprogress()来显示进度。 - osum
3
这是一个AsyncTask的例子。AsyncTask Example - Samir Mangroliya
这是一个异步任务的示例,也包含下载图像的内容: http://www.android-ios-tutorials.com/182/show-progressbar-while-downloading-image-using-asynctask-in-android/ - Houcine
请检查此示例:http://wiki.workassis.com/android-asynctask/ - Bikesh M
1
对于那些尝试在API 30之后实现并发的人来说,AsyncTask已经被弃用了。请参阅文档:public abstract class AsyncTask - ToxicAbe
显示剩余3条评论
21个回答

850

我的完整答案在这里,但这里提供了一张解释性图片,以补充本页面上其他答案的内容。对我来说,在开始时理解所有变量的去向是最令人困惑的部分。

输入图像描述


3
params是一个数组。(在上面的例子中,它是一个 String 数组。)这允许您传递多个相同类型的参数。然后,您可以使用 params[0]params[1]params[2] 等来访问这些参数。在该示例中,params 数组中只有一个 String。如果您需要传递不同类型的多个参数(例如一个 String 和一个 int),请参阅 此问题 - Suragch

715

好的,你正在尝试通过另一个线程访问GUI。总的来说,这不是一个好的实践方式。

AsyncTask 在另一个线程中执行doInBackground() 中的所有内容,该线程无法访问包含视图的GUI。

preExecute()postExecute() 允许在执行新线程中的重型任务之前和之后访问GUI,并且您甚至可以将长时间操作的结果传递给postExecute() 以显示任何处理结果。

请查看下面这些代码行,其中您稍后会更新TextView:

TextView txt = findViewById(R.id.output);
txt.setText("Executed");

将它们放在onPostExecute()中。

然后,在doInBackground完成后,您将看到TextView文本已更新。

我注意到您的onClick监听器没有检查选定的是哪个View。我发现最简单的方法是使用switch语句来实现。下面是一份完整的类,已编辑所有建议以避免混淆。

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

    Button btn;
    AsyncTask<?, ?, ?> runningTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = findViewById(R.id.button1);

        // Because we implement OnClickListener, we only
        // have to pass "this" (much easier)
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // Detect the view that was "clicked"
        switch (view.getId()) {
        case R.id.button1:
            if (runningTask != null)
                runningTask.cancel(true);
            runningTask = new LongOperation();
            runningTask.execute();
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Cancel running task(s) to avoid memory leaks
        if (runningTask != null)
            runningTask.cancel(true);
    }

    private final class LongOperation extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // We were cancelled; stop sleeping!
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed"); // txt.setText(result);
            // You might want to change "executed" for the returned string
            // passed into onPostExecute(), but that is up to you
        }
    }
}

2
我无法执行这个代码 <code> btn.setOnClickListener(this); </code> Eclipse 给出了一个错误 ----- "在 View 类型中,setOnClickListener(View.OnClickListener) 方法不适用于参数 (AsyncTaskActivity)"。 - Fox
1
作为一个附录和谷歌种子(来自一位正在学习这些东西的人,这也是我发现这个问题的原因): 当需要向用户报告进度时,你将会在回调函数 onProgressUpdate 中完成大部分 UI 更新操作,该回调函数在主 UI 线程中执行。 - RichieHH
1
如果您的活动由于任何原因而旋转或销毁,这肯定会出问题... - Sam
@Sam - 是的,但这不是OP所问的。问题与使AsyncTask工作有关,而不是使用它时可能遇到的陷阱或替代方案。 - Graham Smith
好的,只是指出来而已。这可能值得在答案中强调一下(尤其是它被高度赞同),因为这可能是自讨苦吃的简单方法。 - Sam
显示剩余6条评论

77

我相信代码是正常执行的,但你试图在后台线程中更改UI元素,这是不允许的。

请按照以下方式修改调用和AsyncTask:

调用类

注意:我个人建议在您执行AsyncTask线程的任何地方使用onPostExecute(),而不是在扩展AsyncTask本身的类中使用。我认为这样可以使代码更容易阅读,特别是如果您需要在多个位置使用AsyncTask处理略有不同的结果。

new LongThread() {
    @Override public void onPostExecute(String result) {
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(result);
    }
}.execute("");

LongThread类(继承自AsyncTask):

@Override
protected String doInBackground(String... params) {
    for (int i = 0; i < 5; i++) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    return "Executed";
}      

8
感谢提供这个例子,它将AsyncTask与Activity解耦。 - sthomps
2
是的,终于有人将任务和活动解耦了。谢谢。在活动中重写onPostExecute太棒了。 - mcy

64

这里是概念和代码

我创建了一个简单的示例来演示如何使用Android的AsyncTask。它从onPreExecute(),doInBackground(),publishProgress()开始,最后是onProgressUpdate()

在其中,doInBackground()作为后台线程运行,而其他工作则在UI线程中运行。您不能在doInBackground()中访问UI元素。顺序与我提到的相同。

但是,如果您需要从doInBackground更新任何小部件,则可以从doInBackground调用publishProgress,该方法将调用onProgressUpdate以更新UI小部件。

class TestAsync extends AsyncTask<Void, Integer, String> {
    String TAG = getClass().getSimpleName();

    protected void onPreExecute() {
        super.onPreExecute();
        Log.d(TAG + " PreExceute","On pre Exceute......");
    }

    protected String doInBackground(Void...arg0) {
        Log.d(TAG + " DoINBackGround", "On doInBackground...");

        for (int i=0; i<10; i++){
            Integer in = new Integer(i);
            publishProgress(i);
        }
        return "You are at PostExecute";
    }

    protected void onProgressUpdate(Integer...a) {
        super.onProgressUpdate(a);
        Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d(TAG + " onPostExecute", "" + result);
    }
}

在您的活动中这样调用:

new TestAsync().execute();

开发者参考资料在这里


3
Java中的类名通常以大写字母开头,这是一种常见的命名规范。 - Vamsi Pavan Mahesh

22

将这两行移动:

TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");

将AsyncTask的doInBackground方法之外的操作移至onPostExecute方法中。你的AsyncTask应该类似于这样:

private class LongOperation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            Thread.sleep(5000); // no need for a loop
        } catch (InterruptedException e) {
            Log.e("LongOperation", "Interrupted", e);
            return "Interrupted";
        }
        return "Executed";
    }      

    @Override
    protected void onPostExecute(String result) {               
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(result);
    }
}

嘿,我正在服务上运行异步任务,我想将一些值返回到主UI线程。 - Dipen
@Dipen - 请查看此讨论。其中有两个问题:从AsyncTask报告结果,我的答案解决了这个问题;以及从服务发送值到UI线程,另一个讨论解决了这个问题。这些问题是独立的。 - Ted Hopp

16

如何记忆AsyncTask中使用的参数?

不要。

如果你是AsyncTask的新手,写一个AsyncTask时很容易感到困惑。主要原因在于AsyncTask中使用的参数,即AsyncTask<A, B, C>。基于方法的A、B、C(参数)签名的差异会让事情变得更加混乱。

保持简单!

关键是不要记忆。如果你能够想象出你的任务实际上需要做什么,那么第一次尝试使用正确的签名编写AsyncTask就会变得轻而易举。只需要弄清楚你的InputProgressOutput是什么,那么你就可以开始了。

那么AsyncTask是什么?

AsyncTask是在后台线程中运行的后台任务。它接受Input,执行Progress并给出Output

也就是说AsyncTask<Input, Progress, Output>

例如:

Enter image description here

与方法有什么关系?

AsyncTaskdoInBackground()之间的关系。

Enter image description here

doInBackground()onPostExecute()onProgressUpdate()也有关系。

Enter image description here

如何在代码中编写它?

DownloadTask extends AsyncTask<String, Integer, String>{

    // Always same signature
    @Override
    public void onPreExecute()
    {}

    @Override
    public String doInbackGround(String... parameters)
    {
        // Download code
        int downloadPerc = // Calculate that
        publish(downloadPerc);

        return "Download Success";
    }

    @Override
    public void onPostExecute(String result)
    {
        super.onPostExecute(result);
    }

    @Override
    public void onProgressUpdate(Integer... parameters)
    {
        // Show in spinner, and access UI elements
    }

}

你将如何运行这个任务?

new DownLoadTask().execute("Paradise.mp3");

14

背景 / 理论

AsyncTask 允许您在后台线程上运行任务,并将结果发布到 UI 线程。

用户始终应该能够与应用程序进行交互,因此重要的是避免阻塞主(UI)线程,例如从网络下载内容。

这就是为什么我们使用AsyncTask的原因。

它通过包装 UI 线程消息队列和处理程序提供了一个简单的接口,允许您发送和处理来自其他线程的可运行对象和消息

实现

AsyncTask 是一个通用类。 (它在构造函数中采用参数化类型。)

它使用这三个通用类型:

Params - 在执行时发送到任务的参数的类型。

Progress - 在后台计算期间发布的进度单位的类型。

Result - 后台计算结果的类型。

并非总是使用异步任务的所有类型。 要将类型标记为未使用,请简单地使用类型 Void

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

这三个参数对应于您可以在AsyncTask中覆盖的三个主要函数

  • doInBackground(Params...)
  • onProgressUpdate(Progress...)
  • onPostExecute(Result)

执行 AsyncTask

  • 使用要发送到后台任务的参数调用execute()

发生了什么

  1. 主/UI 线程上,调用onPreExecute()

    • 初始化此线程中的某些内容。 (例如,在用户界面上显示进度条。)
  2. 后台线程上,调用doInBackground(Params...)

    • (通过execute传递了Params。)
    • 应该发生长时间运行的任务的地方。
    • 必须至少重写 doInBackground() 来使用 AsyncTask。

    • 调用publishProgress(Progress...)以在后台计算仍在执行时更新用户界面,例如 UI 动画或打印的日志文本。

      • 导致调用onProgressUpdate()
  3. 后台线程上,从 doInBackground() 返回结果。

    • (这会触发下一步。)
  4. 主/UI 线程上,使用返回的结果调用onPostExecute()

例子

在两个示例中,“阻塞任务”都是从 Web 上下载内容。

  • 示例 A 下载图像并在 ImageView 中显示它,而
  • class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bitImage; public DownloadImageTask(ImageView bitImage) { this.bitImage = bitImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mBmp = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mBmp = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mBmp; } protected void onPostExecute(Bitmap result) { bitImage.setImageBitmap(result); } }

    示例 B

     private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
         protected Long doInBackground(URL... urls) {
             int count = urls.length;
             long totalSize = 0;
             for (int i = 0; i < count; i++) {
                 totalSize += Downloader.downloadFile(urls[i]);
                 publishProgress((int) ((i / (float) count) * 100));
                 // Escape early if cancel() is called
                 if (isCancelled()) break;
             }
             return totalSize;
         }
    
         protected void onProgressUpdate(Integer... progress) {
             setProgressPercent(progress[0]);
         }
    
         protected void onPostExecute(Long result) {
             showDialog("Downloaded " + result + " bytes");
         }
     }
    

    例子 B 执行

    new DownloadFilesTask().execute(url1, url2, url3);
    

非常好..但我一直收到有关返回类型冲突的错误 - 尝试使用不兼容的返回类型。我尝试了各种返回类型,但仍然出现相同的错误。 - john k
嗨 @johnktejik,你可能想要搜索那个特定的问题。也许这就是发生在你身上的事情:the-return-type-is-incompatible-with-asynctask - TT--
1
很好!是否考虑进入编辑模式 - Peter Mortensen

12

当执行异步任务时,该任务会经历四个步骤:

  1. onPreExecute()
  2. doInBackground(Params...)
  3. onProgressUpdate(Progress...)
  4. onPostExecute(Result)

下面是一个演示示例:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));

            // Escape early if cancel() is called
            if (isCancelled())
                break;
        }
        return totalSize;
    }

    protected void onProgressUpdate(Integer... progress) {
        setProgressPercent(progress[0]);
    }

    protected void onPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
 }

一旦你创建了一个任务,它会非常简单地执行:

new DownloadFilesTask().execute(url1, url2, url3);

执行程序需要一个 Runnable 参数。它不接受字符串。你的URL是什么类型?是字符串还是其他类型? - user2362956

11

最简单的异步执行操作的示例:

class MyAsyncTask extends android.os.AsyncTask {
    @Override
    protected Object doInBackground(Object[] objects) {
        // Do something asynchronously
        return null;
    }
}

运行它:

(new MyAsyncTask()).execute();

6
我建议您使用这个库来处理后台任务,以便让生活变得更加轻松:

https://github.com/Arasthel/AsyncJobLibrary

。非常简单易用。
AsyncJob.doInBackground(new AsyncJob.OnBackgroundJob() {

    @Override
    public void doOnBackground() {
        startRecording();
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接