AsyncTask
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.
//異步任務能夠適當和容易的使用主線程。這個類允許執行後臺的任務並且在主線程上面宣告結果,在這個過程中不需要使用線程和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 the java.util.concurrent (併發)pacakge such as Executor(執行者), ThreadPoolExecutor and FutureTask.
//AsyncTask被設計作爲對Thread和Handler的一個幫助類,使用時不需要建立一般的線程框架。理想的情況下,AsyncTask被用來執行
短時間的操作(最多幾秒鐘).如果你需要讓線程保持一個較長時間的工作,強烈推薦你使用java.util.concurrent包提供的各種各樣的API,例如Excutor,ThreadPoolExecutor和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.
//在後臺線程裏面執行運算並且將結果顯示在主線程裏面的過程被定義爲一個異步任務。一個異步任務通過三個通用的類型(Params,Progress,Result)和四個步驟(onPreExcute,doInBackground,onProgressUpdate,和onPostExcute)被定義。
//更多的關於任務和線程的信息,參考開發者指南里面的"Progres and Threads "一文。
//Usage用法
AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)
//AsyncTask必須被繼承使用.子類必須重寫至少一個方法(doInBackground(Params...)),大多數情況下也會重寫第二個方法(onPostExcute(Result)).
package com.cdc.asynctaskdemo;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private Button bt;
/** 進度條 **/
private ProgressBar pb;
private Bitmap bitmap;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.bt1);
iv = (ImageView) findViewById(R.id.iv1);
pb = (ProgressBar) findViewById(R.id.pb1);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AsyncImage asyncImage = new AsyncImage();
asyncImage.execute("http://y3.ifengimg.com/a39fc0c47ae80a31/2014/0321/rdn_532bd2fd87276.jpg");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private final class AsyncImage extends AsyncTask<String, Integer, Bitmap> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pb.setVisibility(View.VISIBLE);
}
//後臺進程獲取圖片
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
try {
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
int len = conn.getContentLength();
pb.setMax(len);
InputStream in = null;
for (int i = 1; i <= len; i = i * 2) {
in = conn.getInputStream();
publishProgress(i);
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
/** 在主線程更新UI **/
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//顯示圖片
iv.setImageBitmap(result);
pb.setVisibility(View.GONE);
}
/**** 更新進度條 **/
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
pb.setProgress(values[0]);
}
}
}
佈局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/bt1" />
<ProgressBar
android:id="@+id/pb1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:visibility="invisible"
android:layout_below="@id/bt1" />
<ImageView
android:id="@+id/iv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/bt1"
android:contentDescription="@string/bt1"
>
</ImageView>
</RelativeLayout>