Android 中的AsyncTask
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Android 中的AsyncTask,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1432字,纯文字阅读大概需要3分钟。
内容图文
在后台下载图片,下载完成后更新UI是一个很常见的需求。在没有AsyncTask类之前,我们需要写许多thread和Handler的代码去实现这个功能,有了AsyncTask,一切变得简单了。下面摘抄谷歌官方介绍:
AsyncTask is designed to be a helper class around Thread
and Handler
and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent
pacakge such as Executor
, ThreadPoolExecutor
and FutureTask
.
可以看出AsyncTask并没有引入底层thread技术,仅仅是对Thread 和 Handler的利用而已。并且使用场合也有局限,最多在后台运行几秒,过长运行不应该使用(会产生什么问题?)。
使用AsyncTask必须创建子类,复写指定方法。其中doInBackground和onPostExecute是2个主要的方法。doInBackground在子线程中执行,里面应该写些耗时的方法,onPostExecute在doInBackground完成后在主线程中调用。doInBackground,onPostExecute 分别在子线程和主线程调用,就是AsyncTask的特点。
There are a few threading rules that must be followed for this class to work properly:
- The AsyncTask class must be loaded on the UI thread. This is done automatically as of
JELLY_BEAN
. - The task instance must be created on the UI thread.
-
execute(Params...)
must be invoked on the UI thread. - Do not call
onPreExecute()
,onPostExecute(Result)
,doInBackground(Params...)
,onProgressUpdate(Progress...)
manually. - The task can be executed only once (an exception will be thrown if a second execution is attempted.)
原文:http://www.cnblogs.com/breezemist/p/3851648.html
内容总结
以上是互联网集市为您收集整理的Android 中的AsyncTask全部内容,希望文章能够帮你解决Android 中的AsyncTask所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。