【 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.

Handler和AsyncTask,都是为了不阻塞主线程(UI线程),且UI的更新只能在主线程中完成,因此异步处理是不可避免的。Android的AsyncTask比Handler更轻量级一些(不需要借助线程和Handler即可实现),适用于简单的异步处理。

AsyncTask 在后台运行一些操作然后在UI上展现,不用操作具体的线程和handlers

Three generic types used by an asynchronous task:

  1. Params, the type of the parameters sent to the task upon execution
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.

AsyncTask的特点是任务在主线程之外运行,而回调方法是在主线程中执行,这就有效地避免了使用Handler带来的麻烦。
//AsyncTask.execute()要在主线程里调用 
new AsyncLoader().execute((Void)null);

子类必须实现抽象方法doInBackground(Params… p) ,在此方法中实现任务的执行工作,比如连接网络获取数据等。通常还应该实现onPostExecute(Result r)方法,在此方法中返回应用程序关心的结果

AsyncTask一定要在主线程中创建实例。

The 4 steps

AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,开发者需要做的就是实现这些方法。在任务的执行过程中,这些方法被自动调用

2

  1. 调用开始,onPreExecute(), invoked on the UI thread immediately after the task is executed。当任务执行之前开始调用此方法,可以在这里显示进度对话框。
  2. 在后台运行,doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing。此完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。
  3. 处理进度,onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). 此方法在主线程执行,用于显示任务执行的进度。
  4. 结束,onPostExecute(Result), invoked on the UI thread after the background computation finishes。此方法在主线程执行,任务执行的结果作为此方法的参数返回

(string… params), 三个小点,可变的参数类型,也称为不定参数类型。英文缩写是varargus,即variable argument type。表明这个方法在接收参数的时候,个数是不定的。

refer: 详解Android中AsyncTask的使用

Android AsyncTask理解

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

生活在西班牙

自己动手丰衣足食

BlueAsteroid

Just another WordPress.com site

Jing's Blog

Just another WordPress.com site

Start from here......

我的心情魔方

天才遠私廚

希望能做一個分享各種資訊的好地方

语义噪声

西瓜大丸子汤的博客

笑对人生,傲立寰宇

Just another WordPress.com site

Where On Earth Is Waldo?

A Project By Melanie Coles

the Serious Computer Vision Blog

A blog about computer vision and serious stuff

Cauthy's Blog

paper review...

Cornell Computer Vision Seminar Blog

Blog for CS 7670 - Special Topics in Computer Vision

datarazzi

Life through nerd-colored glasses

Luciana Haill

Brainwaves Augmenting Consciousness

槑烎

1,2,∞

Dr Paul Tennent

and the university of nottingham

turn off the lights, please

A bunch of random, thinned and stateless thoughts around the Web

%d bloggers like this: