使用 AsyncTask 时必须遵守如下规则:
1、必须在 UI 线程中创建 AsyncTask 的实例;
2、必须在 UI 线程中调用 AsyncTask 的 execute() 方法;
3、AsyncTask 的 onPreExecute()、onPostExecute(Result r)、doInBackground(Params... params)、onProgressUpdate(Progress... values) 方法,不应该由开发者调用,而是由系统调用;
4、每个 AsyncTask 只能被执行一次,多次调用将会引发异常。
下面使用一个异步下载任务作为 AsyncTask 的使用示例。
该测试程序需要网络权限,因此需要在 AndroidManifest.xml 中加入申请权限的代码:
<uses-permission android:name="android.permission.INTERNET" />
主布局文件的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="download"
android:text="@string/start" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
主程序的源代码如下:
package com.toby.personal.testlistview;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
final private static String TAG = "Toby_Test";
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView) findViewById(R.id.show);
}
public void download(View view) {
DownloadTask task = new DownloadTask(this);
try {
task.execute(new URL("http://www.jianshu.com/u/7b2ff27d6fd9"));
} catch (Exception e) {
e.printStackTrace();
}
}
private class DownloadTask extends AsyncTask<URL, Integer, String> {
ProgressDialog progressDialog;
int hasRead = 0;
Context context;
DownloadTask(Context context) {
this.context = context;
}
@Override
protected String doInBackground(URL... params) {
StringBuilder stringBuilder = new StringBuilder();
try {
URLConnection connection = params[0].openConnection();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
hasRead++;
publishProgress(hasRead);
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
show.setText(s);
progressDialog.dismiss();
super.onPostExecute(s);
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading");
progressDialog.setMessage("Please wait ...");
progressDialog.setCancelable(false);
progressDialog.setMax(202);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIndeterminate(false);
progressDialog.show();
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
show.setText("Has read " + values[0] + " lines.");
progressDialog.setProgress(values[0]);
super.onProgressUpdate(values);
}
}
}
改程序的运行效果:
参考文献:《疯狂Android讲义(第2版)》