AsyncTask简介

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.


蹩脚翻译 仅供参考


AsyncTask 能使 UI 线程的使用变得恰当和简单。这个类允许 UI 线程在不操纵 Thread 和/或 Handler 的情况下执行后台操作和发布结果。

AsyncTask 被设计成为一个围绕 Thread 和 Handler 工作的帮助类,并且不会形成一个普通的线程框架。AsyncTask 理想中应该被用于短操作(大多是几秒)。如果你需要保持线程运行很长时间,推荐你使用 java.util.concurrent 包提供的许多类比如 Executor、ThreadPoolExecutor 和 FutureTask。

一个 AsyncTask 被定义为一个运行在后台线程并且结果公布给 UI 线程的运算。AsyncTask 定义了三个泛型:Params、Progress 和 Result 以及四个步骤:onPreExecute、doInBackground、onProgressUpdate 和 onPostExecute。


以上摘自 Google 官方文档 。

之前一直使用 Handler+Thread 来完成各种异步操作,昨天参加南京 GDG 这边组织的 Android Study Jam 介绍了一下 AsyncTask 的用法,惭愧于之前一直没有使用正确的姿势来学习 Android,养成了各种不规范的习惯。

在 AsyncTask 中,三个泛型分别代表着:

  • Params:创建时被传入的参数
  • Progress:执行过程中需要及时反馈给 UI 的进度
  • Result:任务执行结束后的结果

四个方法分别表示:

  • onPreExecute:执行前的准备工作。一般用于初始化 UI
  • doInbackground:后台任务
  • onProgressUpdate:进度更新给 UI
  • onPostExecute:返回结果

下面是一个小 demo 来演示一下最基础的 AsyncTask 用法:

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {

ProgressBar pb_main;
TextView tv_result;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

pb_main = (ProgressBar) findViewById(R.id.pb_main);
tv_result = (TextView) findViewById(R.id.tv_main);

TestTask task = new TestTask();
task.execute();
}

private class TestTask extends AsyncTask<Void, Integer, String> {

@Override
protected String doInBackground(Void… params) {

int progress = 0;
while (progress < 100) {
SystemClock.sleep(100);
progress++;
publishProgress(progress);
}
return “任务完成” + progress;
}

@Override
protected void onProgressUpdate(Integer… values) {
pb_main.setProgress(values[0]);
tv_result.setText(“任务进度:” + values[0] + “”);
}

@Override
protected void onPostExecute(String s) {
tv_result.setText(s);
}
}
}

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android"
xmlns:tools=http://schemas.android.com/tools"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“.MainActivity”>

<TextView
android:padding=“20dp”
android:id=“@+id/tv_main”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“@string/progress_info”
android:layout_alignParentTop=“true”
android:layout_centerHorizontal=“true” />

<ProgressBar
android:id=“@+id/pb_main”
style=“?android:attr/progressBarStyleHorizontal”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_centerVertical=“true”
android:layout_alignParentLeft=“true”
android:layout_alignParentStart=“true” />

</RelativeLayout>

Comentarios

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×