上一篇文章和大家分享了 Android怎么在子线程中控制UI线程,接下去分享的是分装了Handler的AnyscTask.Android1.5提供了工具类android.os.AsyncTask,它使创建异步任务变得更加简单,不再需要编写任务线程和Handler实例即可完成相同的任务的。
先看下网上大家总结基本步骤:
1.execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。
2.onPreExecute(),在execute(Params... params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。
3.doInBackground(Params... params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,比如调用接口。此方法将接收输入参数和 返回计算结果。在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。
4.onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上。
5.onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。
在使用的时候,有几点需要格外注意:
1.异步任务的实例必须在UI线程中创建。
2.execute(Params... params)方法必须在UI线程中调用。
3.不要手动调用onPreExecute(),doInBackground(Params... params),onProgressUpdate(Progress... values),onPostExecute(Result result)这几个方法。
4.不能在doInBackground(Params... params)中更改UI组件的信息。
5.一个任务实例只能执行一次,如果执行第二次将会抛出异常。
6. MyTask extends AsyncTask<String, Integer, byte[]>,第一个参数是启动的执行参数,第二个参数是后台进度条的参数,第三个参数是返回的结果集
接下来来看个实例,以异步下载一张图片为例:
public class MainActivity extends Activity {
private Button execute;
private Button cancel;
private ProgressBar progressBar;
private TextView textView;
private MyTask mTask = null;
private static final String TAG = "ASYNC_TASK";
private ImageView imageView1;
private final String IMAGE_PATH = "http://www.baidu.com/img/bd_logo1.png";// 设置网页图片的地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
/**
*
*/
private void initView() {
imageView1 = (ImageView) findViewById(R.id.iv);
execute = (Button) findViewById(R.id.execute);
execute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 注意每次需new一个实例,新建的任务只能执行一次,否则会出现异常
mTask = new MyTask();
new MyTask().execute(IMAGE_PATH);
execute.setEnabled(false);
cancel.setEnabled(true);
}
});
cancel = (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 取消一个正在执行的任务,onCancelled方法将会被调用
mTask.cancel(true);
}
});
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
textView = (TextView) findViewById(R.id.text_view);
}
private class MyTask extends AsyncTask<String, Integer, byte[]> {
/*
* onPreExecute()方法在后台操作开始前运行在UI线程上
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(TAG, "onPreExecute() called");
}
/*
* doInBackground方法运行在后台并处理后台操作
*/
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
textView.setText("loading..." + values + "%");
}
/*
* 一旦后台操作完毕,onPostExecute()方法就会在UI线程中运行
*/
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
/*
* 将下载的bitmap放置在imagView中去 result就是下载的图片
*/
Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
imageView1.setImageBitmap(bitmap);
execute.setEnabled(true);
cancel.setEnabled(false);
}
@Override
protected byte[] doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
byte[] result = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
publishProgress(50);
result = EntityUtils.toByteArray(httpResponse.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
}
}
<span style="white-space:pre"> </span>布局文件:
<span style="white-space:pre"> </span>
<pre name="code" class="html"><?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" >
<Button
android:id="@+id/execute"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="execute" />
<Button
android:id="@+id/cancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="cancel" />
<ProgressBar
android:id="@+id/progress_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</LinearLayout>
至于你的异步操作是什么内容那就根据项目的情况而定,这边仅是加载一张图片:)
demo下载地址:http://download.youkuaiyun.com/detail/u013651405/8927137