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