Essentials系列主要是讲原理和实现,应用可以参考API说明和APIDemo
AsyncTask是android自带的,用于异步调用的一个东西。
别人的轮子
上原版说明。
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.
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 begin, doInBackground, processProgress and end.
原版说明写的蛮好的,3 types, 4 steps.
这里我就不具体说明了,看看Reference就好了。
这里主要还是介绍多线程的应用
Android上面的确有很多需要用到多线程的地方。这个东西很好用。
下面就研究源码
主要先看几个成员变量
/** 一个BlockingQueue,给ThreadPoolExecutor存Task用的。 */
private static final BlockingQueue<Runnable> sWorkQueue =
new LinkedBlockingQueue<Runnable>(10);
/** 一个ThreadFactory,也是给ThreadPoolExecutor用的,计数功能,标识Thread id功能。 */
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
/** ThreadPool*/
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
/** callable, 用于返回thread执行的结果 */
private final WorkerRunnable<Params, Result> mWorker;
//future 和task的混合体。construct method可以传入callable.
// 可以用于获得thread执行结果,cancel thread.
private final FutureTask<Result> mFuture;
constructor
initialize mWorker, mFuture.
execute()
onPreExecute(); // run in UI thread
mWorker.mParams = params;
sExecutor.execute(mFuture);
then invoke
call() in mWorker = new ...
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return
doInBackground(mParams); // run in new thread
}
};
then invoke
done() in mFuture = new ...
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
Message message;
Result result = null;
try {
result = get();
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(AsyncTask.this, result));
message.sendToTarget();
}
};
Let us look up inner class InternalHandler
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult result = (AsyncTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.
onProgressUpdate(result.mData);
break;
case MESSAGE_POST_CANCEL:
result.mTask.onCancelled();
break;
}
}
}
private void finish(Result result) {
if (isCancelled()) result = null;
onPostExecute(result);
mStatus = Status.FINISHED;
}
再看
protected final void publishProgress(Progress... values) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
至此4 steps都看完了。
AsyncTask让你很安全的管理线程。
执行任务,取消任务,实时更新progress, 获得任务执行结果。
别人的轮子,可以拿来用。
看了下,
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
AsyncTask里面的thread pool是static的。
这就是说用AsyncTask,一个APP里面正能同时跑5个thread.另外新启动的要在后面排队。
分享到:
相关推荐
Android AsyncTask用法和异步加载图片通过AsyncTask 从网络上异步加载一张图片
Android AsyncTask的简单Demo,对应Blog文章:http://blog.csdn.net/dolacmeng/article/details/50215519
Android AsyncTask Demo 自己参考网络写的学习 demo
Android AsyncTask异步处理下载网页
AsyncTask 断点下载
代码为博客的示例代码,有问题请博客中留言:http://blog.csdn.net/lmj623565791/article/details/38614699
Android AsyncTask 文章集合
android AsyncTask中更新progressBar 。可用于http请求、下载文件等
Android Asynctask 先小试牛刀,了解一下各个方法执行过程,关注博客http://himici.com/
自己写了一个基于httpurlconnection和Asynctask的例子
android asyncTask的使用,通过简单的实例来说明Task异步类的使用
Android AsyncTask 同步下载图片,先是显示默认的图标,下载完成了立刻显示下载的图标,可以左右切换
Android AsyncTask Demo
在Android中使用AsyncTask和Handler线程间交互的方式,详情参见博客:http://www.cnblogs.com/plokmju/p/android_AsyncTask.html和http://www.cnblogs.com/plokmju/p/android_Handler.html
Android AsyncTask的缺陷和问题总结 在Android开发中,AsyncTask可以使得用户避免直接使用Thread类和Handler 来处理后台操作,适用于需要异步处理数据并将数据更新到界面上的情况。AsyncTask适用于后台操作只有几秒...
AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程. 使用的优点: 简单,快捷 过程...
android AsyncTask的简单使用方法
AsyncTask的用法
简单的android AsyncTask 例子
android asynctask的fragment更新UI(附线程管理) 博客地址:http://blog.csdn.net/qq_16064871