Android 中的AsyncTask

在后台下载图片,下载完成后更新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 ExecutorThreadPoolExecutor 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:

Android 中的AsyncTask,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。