昨天覆習了一下多線程和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);
}
}
}
運行效果: