Android `AsyncTask`简要分析
AsyncTask简要分析
经典异步任务:AsyncTask,使用场景有:批量下载,批量拷贝等。官方文档就直接给出了一个批量下载的示例。
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
// Once created, a task is executed very simply:
new DownloadFilesTask().execute(url1, url2, url3);
这里简单看一下,AsyncTask中的几个经典问题:
AsyncTask开了几个线程?AsyncTask怎么实现的线程调度?
好吧,就想到了这两个问题。第一个问题,明显是坑。答案是未知的。看手机 cpu个数了。
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
然后是第二个问题。简单回答就是一句话,通过开启线程执行具体逻辑,然后通过handler将结果发送到主线程。
进一步追踪的话,就会发现,AsyncTask = ThreadPoolExecutor + Handler 。
通过源码可以看到,AsyncTask在构造方法里面,已经完成了全部的准备工作。
MainHandler已经创建。FutureTask已经准备了。(说实话,FutureTask难过的让人吐血)public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper); mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams); // mParams 核心逻辑
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result); // 核心逻辑
}
return result;
}
}; mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get()); // get()
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
系消息
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
} mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; // 核心逻辑
exec.execute(mFuture); // 核心逻辑 return this;
} // 核心逻辑:handler,将结果发送到主线程
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
Android `AsyncTask`简要分析的更多相关文章
- Android AsyncTask 源代码分析
AsyncTask源代码分析 public abstract class AsyncTask<Params, Progress, Result> { //日志TAG private sta ...
- [Android 动画]简要分析一下Animator 与 Animation
大家假设喜欢我的博客,请关注一下我的微博,请点击这里(http://weibo.com/kifile),谢谢 转载请标明出处(http://blog.csdn.net/kifile),再次感谢 在 A ...
- Android AsyncTask运作原理和源码分析
自10年大量看源码后,很少看了,抽时间把最新的源码看看! public abstract class AsyncTask<Params, Progress, Result> { p ...
- Android初级教程通过简要分析“土司”源码,来自实现定义土司理论探讨
由于系统自带的土司瞬间即逝,而且非常难看.因此我们就希望自定义自己的土司风格.有些实例就是基于自定义土司完成的,例如金山卫士的火箭发射,基本原理就是个土司.但是在做出自己的土司风格之前,还是要简要分析 ...
- Android Hal层简要分析
Android Hal层简要分析 Android Hal层(即 Hardware Abstraction Layer)是Google开发的Android系统里上层应用对底层硬件操作屏蔽的一个软件层次, ...
- Android异步任务处理框架AsyncTask源代码分析
[转载请注明出处:http://blog.csdn.net/feiduclear_up CSDN 废墟的树] 引言 在平时项目开发中难免会遇到异步耗时的任务(比方最常见的网络请求).遇到这样的问题.我 ...
- Android Debuggerd 简要介绍和源码分析(转载)
转载: http://dylangao.com/2014/05/16/android-debuggerd-%E7%AE%80%E8%A6%81%E4%BB%8B%E7%BB%8D%E5%92%8C%E ...
- Android 5.1 Settings源代码简要分析
转载请注明出处,谢谢~http://blog.csdn.net/u011974987/article/details/51004854. 概述: 先声明:本人工作快两年了,仍是菜鸟级别的.羞愧啊!曾经 ...
- Android APP性能分析方法及工具
近期读到<Speed up your app>一文.这是一篇关于Android APP性能分析.优化的文章.在这篇文章中,作者介绍他的APP分析优化规则.使用的工具和方法.我觉得值得大家借 ...
随机推荐
- 螺旋队列和hiho1525逃离迷宫3
我是真调不出错误了! hiho1525逃离迷宫3 #include <stdio.h> #include <stdlib.h> #include <math.h> ...
- centos7搭建ELK Cluster集群日志分析平台
应用场景:ELK实际上是三个工具的集合,ElasticSearch + Logstash + Kibana,这三个工具组合形成了一套实用.易用的监控架构, 很多公司利用它来搭建可视化的海量日志分析平台 ...
- CentOS 6.8下安装python的redis支持库
方法很简单,SSH登录下输入: pip install redis 或者 easy_install redis 如果上面的方法不行的话,就要尝试编译安装了 wget https://pypi.pyth ...
- Tomcat权威指南-读书摘要系列9
从源代码组建Tomcat 安装Apache Ant ant是make的开放源代码的替代品,而且是专门为java程序语言设计. Ant的最初用途是作为Tomcat的组建工具: 之后,Ant成为Java软 ...
- DataGridView更新数据到数据库
WinFrom程序绑定了一个DataGridView控件,我需要添加一个button按钮来更改状态,还需要把更新之后的状态更新到数据库,如下图所示的这样: 首先先来拖控件,把界面做出来,自己拖一个Da ...
- python---django中STATIC_ROOT和STATIC_URL以及STATICFILES_DIRS
先引入两篇相关文章,从中了解更为详细 django 静态资源配置详解 django静态文件配置 Django的STATIC_ROOT和STATIC_URL以及STATICFILES_DIRS(先看) ...
- angularJs的各种服务和指令的使用场景
$location服务,获取页面跳转带的参数 比如说页面是这样的 localhost:9102/admin/goods.html#?id=123 如何获取这个id=123的值呢?????(注意: ...
- POJ-2253 Frogger(最短路)
https://vjudge.net/problem/POJ-2253 题意 公青蛙想到母青蛙那里去,期间有许多石头,公青蛙可以通过这些石头跳过去.问至少要跳的最大距离,即所有路径上石头间的最大距离的 ...
- 20155339 2016-2017-2 《Java程序设计》第8周学习总结
20155339 2016-2017-2 <Java程序设计>第8周学习总结 教材学习内容总结 第十四章NIO与NIO2 NIO使用频道来衔接数据节点,在处理数据时,NIO可以让你设定缓冲 ...
- 第9月第3天 uilabel contentscale
1. http://blog.csdn.net/u012703795/article/details/43706449