您的位置:首页 > 其它

AsyncTask

2016-02-23 18:10 302 查看

AsyncTask

AsyncTask的设计目标是比较短的操作(最多几秒),如果希望执行更长时间,使用 java.util.concurrent 中的 Executor, ThreadPoolExecutor, FutureTask更合适。

Asyntask的泛型实现:

Params:发送给Asyntask的执行参数类型

Progress:the type of the progress units published during the background computation

Result: background计算阶段的结果类型

Asyntask执行中的四步:

onPreExecute() : 任务执行前执行,一般用途例如显示加载框,进度条

doInBackground(Params...) : 执行后台任务(途中可更新进度条)

onProgressUpdate(Progress...) : 更新进度条

onPostExecute(Result) :

注意点

Asyntask实例必须在UI线程中简历

execute(Params...)必须在UI线程中调用。

new DownloadFilesTask().execute(urlStr);


不要手动调用onPreExecute(), onPostExecute()..等方法

The task can be executed only once(an exception will be thrown if a second execution is attempted)

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 or onPreExecute(), and refer to them in doInBackground(Params...)

Set member fields in doInBackground(Params...), and refer to them in onProgressUpdate(Progress...) and onPostExecute(Result)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: