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中的几个经典问题:

  1. AsyncTask开了几个线程?
  2. 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`简要分析的更多相关文章

  1. Android AsyncTask 源代码分析

    AsyncTask源代码分析 public abstract class AsyncTask<Params, Progress, Result> { //日志TAG private sta ...

  2. [Android 动画]简要分析一下Animator 与 Animation

    大家假设喜欢我的博客,请关注一下我的微博,请点击这里(http://weibo.com/kifile),谢谢 转载请标明出处(http://blog.csdn.net/kifile),再次感谢 在 A ...

  3. Android AsyncTask运作原理和源码分析

    自10年大量看源码后,很少看了,抽时间把最新的源码看看! public abstract class AsyncTask<Params, Progress, Result> {     p ...

  4. Android初级教程通过简要分析“土司”源码,来自实现定义土司理论探讨

    由于系统自带的土司瞬间即逝,而且非常难看.因此我们就希望自定义自己的土司风格.有些实例就是基于自定义土司完成的,例如金山卫士的火箭发射,基本原理就是个土司.但是在做出自己的土司风格之前,还是要简要分析 ...

  5. Android Hal层简要分析

    Android Hal层简要分析 Android Hal层(即 Hardware Abstraction Layer)是Google开发的Android系统里上层应用对底层硬件操作屏蔽的一个软件层次, ...

  6. Android异步任务处理框架AsyncTask源代码分析

    [转载请注明出处:http://blog.csdn.net/feiduclear_up CSDN 废墟的树] 引言 在平时项目开发中难免会遇到异步耗时的任务(比方最常见的网络请求).遇到这样的问题.我 ...

  7. 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 ...

  8. Android 5.1 Settings源代码简要分析

    转载请注明出处,谢谢~http://blog.csdn.net/u011974987/article/details/51004854. 概述: 先声明:本人工作快两年了,仍是菜鸟级别的.羞愧啊!曾经 ...

  9. Android APP性能分析方法及工具

    近期读到<Speed up your app>一文.这是一篇关于Android APP性能分析.优化的文章.在这篇文章中,作者介绍他的APP分析优化规则.使用的工具和方法.我觉得值得大家借 ...

随机推荐

  1. HDU 2255 KM算法 二分图最大权值匹配

    奔小康赚大钱 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Subm ...

  2. 滚动条事件,当页面滚动到距顶部一定高度时某DIV自动隐藏和显示

    $(function () {                        //绑定滚动条事件              //绑定滚动条事件            $(window).bind(&q ...

  3. git 中断 merge

    git 版本 >= 1.6.1 git reset --merge git 版本 >= 1.7.4 git merge --abort

  4. C++11 & C++14 & C++17新特性

    C++11:C++11包括大量的新特性:包括lambda表达式,类型推导关键字auto.decltype,和模板的大量改进. 新的关键字 auto C++11中引入auto第一种作用是为了自动类型推导 ...

  5. 鸟哥的Linux私房菜——第十九章:例行命令的建立

    视频链接:http://www.bilibili.com/video/av11008859/ 1. 什么是例行性命令 (分为两种,一种是周期性的,一种是突发性的)1.1 Linux 工作排程的种类: ...

  6. RESTful记录-RESTful服务

    按照REST架构,一个RESTful Web服务不应该继续服务器的客户端的状态.这种限制被称为无状态.它负责客户以它的上下文传递给服务器,然后服务器可以存储这样的上下文,以处理客户端的进一步请求.例如 ...

  7. Rime中州韵导入QQ五笔词库

    过程记录如下: 1.在QQ五笔中导出QQ五笔系统词库 2.使用「深蓝词库转换」转换QQ五笔系统词库,输入源修改为”五笔86版“,输出方式修改为Rime中州韵-五笔. 3.在Ubuntu中打开Termi ...

  8. git 学习小记之图形化界面客户端

    习惯了 Windows 的用户,一直不喜欢用类似命令行的东西来操作,当然我也不是不喜欢,只是操作太慢了.也许 Linux 大神在命令行的帮助下,办事效率翻倍,那也是非常常见的事情..当然我不是大神,所 ...

  9. 编写 grunt 插件经验

    第一步: 先生成插件模板: 利用命令生成, 首先通过github工具获取gruntplugin模板文件: 第二步: 了解plugin/tasks/taskName.js的registerMultiTa ...

  10. HDU 2056 龟兔赛跑 (DP)

    题意:见题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2059 解题报告:以前一直没看出来这题是个DP题,知道是DP题就简单了 .首先要把起点和终点看成 ...