优点:封装了handler+thread+线程池
特点:1、android中已经写好了的多线程
2、处理UI Thread和worker
代码示例:
KateAsycTask task = new KateAsycTask();
task.execute(url,1+"");
class KateAsycTask extends AsyncTask<String, Integer, Bitmap>{
private InputStream inputStream;
private final String SD_CARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
private int maxLength;
private FileOutputStream outputStream;
/**
* 运行在主线程:在异步任务执行之前调用()
* 主要做一些初始化
*/
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
/**
* 在子线程中执行:执行下载任务
*/
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap =null;
String imageUrl = params[0];//String s = params[1];
try {
//1,创建url
URL url = new URL(imageUrl);
//2,打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3,设置请求方式
conn.setRequestMethod("GET");
//4,设置超时时间
conn.setConnectTimeout(5000);
if(conn.getResponseCode() == 200){
maxLength = conn.getContentLength();
//设置进度条的最大值
pb.setMax(maxLength);
inputStream = conn.getInputStream();
//为主线程中的imageView设置图片----
//bitmap = BitmapFactory.decodeStream(inputStream);
String fileName = imageUrl.substring(imageUrl.lastIndexOf("/")+1);
outputStream = new FileOutputStream(SD_CARD_PATH+"/"+ fileName);
int len = 0;
byte[] buffer = new byte[1024];
while((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer, 0, len);
//更新进度条---不能在这里更新:onProgressUpdate
//onProgressUpdate(len);
publishProgress(len);//触发调用onProgressUpdate
}
bitmap = BitmapFactory.decodeFile(SD_CARD_PATH+"/"+fileName);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(outputStream!=null){
outputStream.close();
}
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return bitmap;
}
/**
* 在主线程中执行:接收异步任务下载的进度 更新UI线程的控件
*/
@Override
protected void onProgressUpdate(Integer... values) {
pb.setProgress(pb.getProgress()+values[0]);
String text = "下载进度:"+100 * pb.getProgress() / maxLength+ "%" ;
progressText.setText(text);
super.onProgressUpdate(values);
}
/**
* 在主线程中执行:接收异步线程返回的结果
*/
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
iv_Image.setImageBitmap(result);
}
/**
* 取消异步任务(终止)
*/
@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
asynctask执行异步任务的源码分析
1, public AsyncTask()
初始化了 mWorker(runnable) mFuture(task)
2, task.execute(Params... params)
executeOnExecutor(sDefaultExecutor, params);
onPreExecute();
exec.execute(mFuture);
sDefaultExecutor.execute(mFuture);
SerialExecutor.execute(mFuture);
mFuture(mWorker).run();
callback.call();
mWorker.call();
doInBackground(mParams)
postResult
通过Handler发送消息:MESSAGE_POST_RESULT
3,InternalHandler extends Handler
MESSAGE_POST_RESULT:
onPostExecute(result);
MESSAGE_POST_PROGRESS
onProgressUpdate(result.mData);
4, publishProgress(Progress... values)
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
5, 通过线程工厂来 创建线程 :
ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}