IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> AsyncTask源码解析 -> 正文阅读

[移动开发]AsyncTask源码解析

AsyncTask 抽象泛型类
内部实现原理是2个线程池和Handler
泛型<Params,Progress,Result>
Params 为参数类型 ? ?progress 为后台任务执行进度的类型 ? Result返回结果的类型
四个方法
onPreExecute()在主线程中执行。在任务执行前做一些准备
doInBackground(Params... params) 在线程中执行。执行一些比较耗时的操作,可以使用publishProgress(Progress...values)来更新进度信息
onProgressUpdate(Progress... values) 在主线程中执行,此方法可以对控件进行更新
onPostExecute(Result result) 在主线程中执行。当后台任务执行完成后,返回的结果


AsyncTask.class
private final WorkerRunnable<Params,Result> mWorker;
private final FutureTask<Result>mFuture;

// 构造方法

AsyncTask(){//?定义了WorkerRunnable和FutureTask
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);//实现了doInBackground抽象方法
? ? ? ? ? ? ? ? ? ? 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());
? ? ? ? ? ? ? ? } 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);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? };

// 执行方法

Executor(){// 初始化一个串行的线程池SerialExecutor来执行FutureTask
exec.execute(mFuture)
private static class SerialExecutor implements Executor {
? ? ? ? final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();// 任务队列(排序任务)
? ? ? ? Runnable mActive;

? ? ? ? public synchronized void execute(final Runnable r) {
? ? ? ? ? ? mTasks.offer(new Runnable() {// 将FutureTask任务存到mTask任务队列中
? ? ? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? ? ? r.run();// FutureTask的run方法会执行到WorkerRunnable的call方法
? ? ? ? ? ? ? ? ? ? } finally {
? ? ? ? ? ? ? ? ? ? ? ? scheduleNext();// 任务添加到队列之后
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? });
? ? ? ? ? ? if (mActive == null) {
? ? ? ? ? ? ? ? scheduleNext();
? ? ? ? ? ? }
? ? ? ? }

? ? ? ? protected synchronized void scheduleNext() {
? ? ? ? ? ? if ((mActive = mTasks.poll()) != null) {
? ? ? ? ? ? ? ? THREAD_POOL_EXECUTOR.execute(mActive);//取出队列中的任务,提交给Thread_POOL_EXECUTOR线程池来处理
? ? ? ? ? ? }
? ? ? ? }
? ? }
THREAD_POOL_EXECUTOR 指的是threadPoolExecutor
Thread_POOL_EXECUTOR.execute(mActive)执行任务,会执行FutureTask的run方法,
然后调用到WorkerRunnable的call方法会将结果postResult提交出去
private Result postResult(Result result) {
? ? ? ? @SuppressWarnings("unchecked")
? ? ? ? Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
? ? ? ? ? ? ? ? new AsyncTaskResult<Result>(this, result));
? ? ? ? message.sendToTarget();
? ? ? ? return result;
? ? }
getHandler() 在当前线程为UI线程时等价于 getMainHandler()
private static Handler getMainHandler() {
? ? ? ? synchronized (AsyncTask.class) {
? ? ? ? ? ? if (sHandler == null) {
? ? ? ? ? ? ? ? sHandler = new InternalHandler(Looper.getMainLooper());
? ? ? ? ? ? }
? ? ? ? ? ? return sHandler;
? ? ? ? }
? ? }
?? ?
private static class InternalHandler extends Handler {
? ? ? ? public InternalHandler(Looper looper) {
? ? ? ? ? ? super(looper);
? ? ? ? }

? ? ? ? @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
? ? ? ? @Override
? ? ? ? public void handleMessage(Message msg) {
? ? ? ? ? ? AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
? ? ? ? ? ? switch (msg.what) {
? ? ? ? ? ? ? ? case MESSAGE_POST_RESULT:// 接收到MESSAGE_POST_RESULT消息后,会调用
? ? ? ? ? ? ? ? ? ? // There is only one result
? ? ? ? ? ? ? ? ? ? result.mTask.finish(result.mData[0]);//回调onPostExecute(result)
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? case MESSAGE_POST_PROGRESS:
? ? ? ? ? ? ? ? ? ? result.mTask.onProgressUpdate(result.mData);
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? }
? ? }

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-12-03 13:09:04  更:2021-12-03 13:11:22 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年10日历 -2024/10/26 12:22:16-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码