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)被定义。
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)被定义。
开发者指南:
For more information about using tasks and threads, read the Processes and Threads developer guide.
//更多的关于任务和线程的信息,参考开发者指南里面的"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)).
//更多的关于任务和线程的信息,参考开发者指南里面的"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>