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. 使用 yield 减少内存消耗

    php 里面想要处理一个文本文件,有一个方法是使用 file() 函数,但是这个函数会读取文件所有内容,可能会导致占用很大内存. // 28.1 M 的文本文件, 200w 行 $file = 'st ...

  2. python的内置模块random随机模块方法详解以及使用案例(五位数随机验证码的实现)

    1.random(self): Get the next random number in the range [0.0, 1.0) 取0到1直接的随机浮点数 import random print( ...

  3. webpack实现“热更新”和“热加载”(webpack3.6新增)

    之前的博文有提到怎么样去实现热更新,但是居然要用到另外一个node框架(express)而且新增了一个入口(entry)两个插件(plugin)来实现,大大提高了配置的复杂度,这样其实对使用webpa ...

  4. python中的无参装饰器和有参装饰器

    python中的无参装饰器和有参装饰器 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 装饰器特点: 1>.开放封闭原则,即对扩展是开放的,对修改时封闭的: 2>.装饰器 ...

  5. amipy exampes

    jupyter notebook of backtest examples using amipy amipy examples: http://nbviewer.jupyter.org/github ...

  6. 强悍的CSS工具组合:Blueprint, Sass, Compass

    掌握CSS是每个Web开发者的基本要求,虽然CSS本身并不复杂,但怎样写出支持所有主流浏览器(特别是IE)的CSS,以及在大型网站中如何有序地组织好CSS结构却是一个相当棘手的问题.我更多的是一个开发 ...

  7. 交互题(二分)(D. Game with modulo)

    题目链接:http://codeforces.com/contest/1104/problem/D 题目大意:给出一个式子 x%a y%a,会返回结果,如果返回x代表x%a>=y%a.如果返回y ...

  8. mysql内连接、左连接、右连接

    内连接(INNER JOIN)(典型的连接运算,使用像   =   或   <>   之类的比较运算符).包括相等连接和自然连接. 内连接使用比较运算符根据每个表共有的列的值匹配两个表中的 ...

  9. linux笔记_day12_shell编程

    1.shell中如何进行算术运算 A=1 B=2 1)let 算术运算表达式 let C=$A+$B 2)$[算术运算表达式] C=$[$A+$B] 3)$(($A+$B)) 4) expr 算术表达 ...

  10. 第一篇:初始Golang

    Golang简介 编程语言已经非常多,偏性能敏感的编译型语言有 C.C++.Java.C#.Delphi和Objective-C 等,偏快速业务开发的动态解析型语言有PHP.Python.Perl.R ...