当前位置: 首页 > news >正文

【Android】使用AsyncTask来处理一些简单的需要后台处理的动作


[0]首先让我们看看官网上是怎么解释AsyncTask的:

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, calledParams,ProgressandResult, and 4 steps, calledonPreExecute,doInBackground,onProgressUpdateandonPostExecute.

简单的来说AsyncTask就是一个简单的用来避免UI阻塞的,运行在background的工具线程类。我们不需要人工来处理这个线程的生命周期,而是按照一定的规则来执行的。

这个Task有3个参数,分别是传入的参数(Params),执行过程中产生的参数(Process),与最后任务结束返回的结果(Result)。如果有不需要的参数,可以用Void来替代。

有4个步骤,分别是:

onPreExecute():用来处理任务执行前需要做的初始化

doInBackground():真正开始在后台执行操作的步骤(这个是必须override的步骤),在这个步骤中可以使用publishProgress(progress……)来提供用于与UI交互显示信息

onProgressUpdate():用来执行过程中即时显示处理进度的函数(获取到doInBackground里面传递过来的参数而进行显示)

onPostExecute();任务执行结束后做的事情


[1]下面是一个简单的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)); } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
要让一个Task开始执行,只需要像下面这样:

new DownloadFilesTask().execute(url1, url2, url3);


[2]那么如何取消一个AsyncTask呢?

A task can be cancelled at any time by invokingcancel(boolean). Invoking this method will cause subsequent calls toisCancelled()to return true. After invoking this method,onCancelled(Object), instead ofonPostExecute(Object)will be invoked afterdoInBackground(Object[])returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value ofisCancelled()periodically fromdoInBackground(Object[]), if possible (inside a loop for instance.)

我们可以在任何时候call cancel(boolean)的方法来取消一个Task,如果呼叫到这个方法会导致之后呼叫isCancelled()返回true.那么如果这样的话,之后会用onCancelled(Object)来替代onPostExecute(Object)的执行。

为了确保这个Task能够尽快被取消,我们需要在doInBackground(Object[])执行的时候去checkisCancelled()

[3]使用Thread需要注意的事项:

  • The task instance must be created on the UI thread.(这个task必须在UI thread中创建)
  • execute(Params...)must be invoked on the UI thread.(必须在UI thread中叫起执行task)
  • Do not callonPreExecute(),onPostExecute(Result),doInBackground(Params...),onProgressUpdate(Progress...)manually.(不要手动去呼叫那4个方法)
  • The task can be executed only once (an exception will be thrown if a second execution is attempted.) (这个task必须是单次执行的,不要在这个任务没有结束前再次呼叫)
[4]下面两个行为是安全的,因为AsyncTask的所有callback function都是synchronized.

AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.

  • Set member fields in the constructor oronPreExecute(), and refer to them indoInBackground(Params...).
  • Set member fields indoInBackground(Params...), and refer to them inonProgressUpdate(Progress...)andonPostExecute(Result).


写的不好,请多指教,谢谢!




相关文章:

  • 如何让你的网页加载时间降低到 1s 内
  • 洛谷 [P1118] IOI1994 数字三角形
  • C#中 一次执行多条带GO的sql语句
  • 贪吃蛇-需求分析
  • C#正则表达式(RegEx)高级应用之分组(Group)替换(Replace)
  • algorithm.sty not found error in LaTeX 解决方法
  • C# regex replace
  • linux 的 awk 使用
  • Linux启动检测磁盘失败
  • 简历已经过时了,而这里正是你需要的
  • 虚拟机RAC的ASM磁盘组坏块导致重建DB
  • ASP.NET 5 入门 (2) – 自定义配置
  • hadoop进阶
  • 程序员编程艺术第一~二十二章集锦与总结(教你如何编程)
  • C语言的内存分配
  • (ckeditor+ckfinder用法)Jquery,js获取ckeditor值
  • 「前端」从UglifyJSPlugin强制开启css压缩探究webpack插件运行机制
  • 【Leetcode】104. 二叉树的最大深度
  • 【跃迁之路】【585天】程序员高效学习方法论探索系列(实验阶段342-2018.09.13)...
  • - C#编程大幅提高OUTLOOK的邮件搜索能力!
  • git 常用命令
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • js 实现textarea输入字数提示
  • Next.js之基础概念(二)
  • SpringCloud集成分布式事务LCN (一)
  • ubuntu 下nginx安装 并支持https协议
  • WordPress 获取当前文章下的所有附件/获取指定ID文章的附件(图片、文件、视频)...
  • 大型网站性能监测、分析与优化常见问题QA
  • 互联网大裁员:Java程序员失工作,焉知不能进ali?
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 聊一聊前端的监控
  • ​业务双活的数据切换思路设计(下)
  • ${ }的特别功能
  • (1)Nginx简介和安装教程
  • (3)(3.5) 遥测无线电区域条例
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (java)关于Thread的挂起和恢复
  • (附源码)计算机毕业设计ssm基于B_S的汽车售后服务管理系统
  • (三)mysql_MYSQL(三)
  • (一)kafka实战——kafka源码编译启动
  • (一)Linux+Windows下安装ffmpeg
  • (转)利用ant在Mac 下自动化打包签名Android程序
  • ./configure、make、make install 命令
  • .net core 客户端缓存、服务器端响应缓存、服务器内存缓存
  • .Net Framework 4.x 程序到底运行在哪个 CLR 版本之上
  • .net framwork4.6操作MySQL报错Character set ‘utf8mb3‘ is not supported 解决方法
  • .NET Micro Framework初体验(二)
  • .Net Remoting常用部署结构
  • .NET:自动将请求参数绑定到ASPX、ASHX和MVC(菜鸟必看)
  • .NET国产化改造探索(三)、银河麒麟安装.NET 8环境
  • /proc/vmstat 详解
  • ??在JSP中,java和JavaScript如何交互?
  • @拔赤:Web前端开发十日谈
  • [C++]类和对象【上篇】
  • [CareerCup] 12.3 Test Move Method in a Chess Game 测试象棋游戏中的移动方法