Android应用开发学习笔记之AsyncTask

时间:2021-12-08 18:03:20

作者:刘昊昱

博客:http://blog.csdn.net/liuhaoyutz

在上一篇文章中我们学习了多线程和Handler消息处理机制,如果有计算量比较大的任务,可以创建一个新线程执行计算工作,但是子线程无法更新UI界面,所以通过Handler消息处理机制与UI线程通信,更新UI界面。

有一个问题需要注意,创建的子线程太多时,会影响系统性能。针对这个问题,Android为我们提供了代替使用Thread和Handler的方案,这就是AsyncTask。下面看Android官方文档对AsyncTask的描述:

AsyncTask enables properand easy use of the UI thread. This class allows to perform backgroundoperations and publish results on the UI thread without having to manipulatethreads and/or handlers.

AsyncTask is designed tobe a helper class around Thread and Handler anddoes not constitute a generic threading framework. AsyncTasks should ideally beused for short operations (a few seconds at the most.) If you need to keepthreads running for long periods of time, it is highly recommended you use thevarious APIs provided by thejava.util.concurrent pacakgesuch as ExecutorThreadPoolExecutor and FutureTask.

An asynchronous task isdefined by a computation that runs on a background thread and whose result ispublished on the UI thread. An asynchronous task is defined by 3 generic types,called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

下面看一个使用AsyncTask的例子,该程序运行效果如下:

Android应用开发学习笔记之AsyncTask

先来看主布局文件,其内容如下:

<?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" > <TextView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:id="@+id/textView"
android:textSize="20dp"
android:gravity="center" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_gravity="center"
android:textSize="20dp"
android:text="启动AsyncTask" /> </LinearLayout>

下面看主Activity文件,其内容如下:

package com.liuhaoyu;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public classMainActivity extends Activity {
private static final String TAG = "liuhaoyu";
TextViewtextView;
Buttonbutton; /** Called when the activity is firstcreated. */
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); textView = (TextView)findViewById(R.id.textView);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){ @Override
public void onClick(View v) {
// TODO Auto-generated method stub
MyAsyncTaskasyncTask = newMyAsyncTask();
asyncTask.execute(1000);
}
});
} classMyAsyncTask extends AsyncTask<Integer, Integer, String>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Log.d(TAG, "onPreExecute");
} @Override
protected StringdoInBackground(Integer... params) {
// TODO Auto-generated method stub
Log.d(TAG, "doInBackground");
for(int i = 0; i < 10; i++)
{
publishProgress(i);
try {
Thread.sleep(params[0]);
}catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d(TAG, "Background work over");
return "Background work over.";
} @Override
protected voidonProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Log.d(TAG, "onProgressUpdate");
textView.setText(Integer.toString(values[0]));
} @Override
protected void onPostExecute(Stringresult) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d(TAG, "onPostExecute, result = " + result);
}
}
}

打印的LOG信息如下:

Android应用开发学习笔记之AsyncTask