昨天复习了一下多线程和handler的用法,今天再来分享下AsyncTask的用法,虽然很基础,但是很重要。
AsyncTask的介绍,引用一下官网的英文doc:
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 thejava.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
.
一些注意事项:
1.AsyncTask必须在主线程创建。
2.execute()只能调用一次。
3.execute()必须在主线程执行。
ps:AsyncTask占用的内存大于使用handler
那么写一个小demo:
1.新建项目,编写xml布局:
<?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:orientation="vertical" >
<Button
android:layout_margin="20dp"
android:id="@+id/btn_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始下载"/>
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"/>
</LinearLayout>
2.在MainActivity中定义事件,我直接写了一个继承AsyncTask的内部类:
package com.zero.asynctaskdemo;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
* @author dh AsyncTask的简单使用 在后台下载一张图片,屏幕显示。
*/
public class MainActivity extends Activity {
private Button btn;
private ImageView img;
public Bitmap bitmap;
//URL的是本人存储在七牛云上的一张照片,你可以换
private String url[] = {"http://carousel.qiniudn.com/01.jpg"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//执行任务
new DownlodImageTask().execute(url);
}
});
}
private void initView() {
btn = (Button) findViewById(R.id.btn_start);
img = (ImageView) findViewById(R.id.img);
}
// 构造方法:第一个参数URL是doInBackground方法的参数,第三个Long是doInBackground方法的返回值
// 第二的参数Integer用来设置进度,与onProgressUpdate方法对应
private class DownlodImageTask extends AsyncTask<String, Integer, Long> {
// 必须重写的方法,在后台执行耗时任务
@Override
protected Long doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// 修改UI
@Override
protected void onPostExecute(Long result) {
img.setImageBitmap(bitmap);
super.onPostExecute(result);
}
}
}
运行效果: