自己动手写AsyncTask
本文依赖上一篇文章:自己动手写消息机制
在javaSE中模拟Android的AsyncTask异步任务
package com.zhanjixun;
public abstract class AsyncTask<Params, Progress, Result> {
private static final int onProgress = 1;
private static final int onPost = 2;
private boolean exeuted = false;// 实现一个任务只能执行一次
private Handler mHandler = new Handler() {
@SuppressWarnings("unchecked")
public void handlerMessage(Message message) {
if (message.what == onProgress) {
onProgressUpdate((Progress[]) message.obj);
}
if (message.what == onPost) {
onPostExecute((Result) message.obj);
}
}
};
/**
* 在执行后台任务之前,在主线程调用
*/
protected void onPreExecute() {
}
/**
* 执行后台任务的代码都放在这里
*
* @param params
*/
protected abstract Result doInBackground(Params... params);
protected void onProgressUpdate(Progress... progress) {
}
/**
* 在执行后台任务之后,在主线程调用
*/
protected void onPostExecute(Result params) {
}
/**
* 发送一个消息到主线程中,这是过程是异步的,就是说后台任务发送了消息给主线程之后马上继续往下运行
*
* @param progress
*/
protected final void publishProgress(Progress... progress) {
Message msg = new Message();
msg.what = onProgress;
msg.obj = progress;
mHandler.sendMessage(msg);
}
public final void execute(Params... params) {
if (exeuted) {
throw new RuntimeException("不能运行两次");
}
onPreExecute();
// 简单来就好了,直接启动新的线程,而Android中的AsyncTask的各个子类的任务是同步的,这里是异步的
new Thread(new Runnable() {
@Override
public void run() {
Result result = doInBackground(params);
exeuted = true;// 执行完了
Message msg = new Message();
msg.what = onPost;
msg.obj = result;
mHandler.sendMessage(msg);
}
}).start();
}
}
测试类:
package com.zhanjixun.test;
import java.util.Random;
import com.zhanjixun.AsyncTask;
import com.zhanjixun.Looper;
public class AsyncTaskDemo {
public static void main(String[] args) {
Looper.prepare();// 将主线程变成轮询线程
new MyAsyncTask().execute();
Looper.loop();
}
/**
* 模拟下载文件
*
* @author doudian
*
*/
public static class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
int count = 0;
Random random = new Random();
while (count <= 100) {
String format = String.format("后台中下载文件(%d/100)...(%s线程打印)",
count, Thread.currentThread().getName());
System.err.println(format);
publishProgress(count);
// 耗时下载
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
int nextInt = random.nextInt(20);
count += nextInt;
}
return true;
}
@Override
protected void onProgressUpdate(Integer... progress) {
String format = String.format("【提示用户】正在下载文件(%d/100)...(%s线程打印)",
progress[0], Thread.currentThread().getName());
System.out.println(format);
}
@Override
protected void onPostExecute(Boolean params) {
String object = params ? "成功" : "失败";
String format = String.format("任务结束,下载文件%s(%s线程打印)", object, Thread
.currentThread().getName());
System.out.println(format);
}
}
}
测试结果具有随机性:
源代码:http://download.csdn.net/detail/zhanjixun/9583224
还没有评论,来说两句吧...