`
yezhiqiu-love
  • 浏览: 169266 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

andorid AsyncTask 异步更新UI

阅读更多

AsyncTask

extends Object

java.lang.Object
   ↳ android.os.AsyncTask<Params, Progress, Result>

Class Overview

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.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

Usage

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...) ), and most often will override a second one (onPostExecute(Result) .)

Here is an example of subclassing:

 

 


 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
 

Once created, a task is executed very simply:

 new DownloadFilesTask().execute(url1, url2, url3);
 

AsyncTask's generic types

The three types used by an asynchronous task are the following:

  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.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void :

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }
 

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute() , invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...) , invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...) , invoked on the UI thread after a call to publishProgress(Progress...) . The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result) , invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean) . Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object) , instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]) , if possible (inside a loop for instance.)

Threading rules

There are a few threading rules that must be followed for this class to work properly:

Memory observability

AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.

分享到:
评论

相关推荐

    Android异步处理二:使用AsyncTask异步更新UI界面

    Android异步处理二:使用AsyncTask异步更新UI界面。

    Android 使用AsyncTask异步更新UI界面

    3. **LiveData和ViewModel**(自Android架构组件):用于数据绑定和生命周期感知,简化UI更新。 综上所述,虽然`AsyncTask`在早期的Android开发中广泛使用,但随着Android平台的演进,开发者应逐渐转向更现代的异步...

    Android AsyncTask用法和异步加载图片.rar

    本资料包主要讲解了如何使用`AsyncTask`进行异步加载图片,这对于在UI线程中保持流畅用户体验至关重要。 `AsyncTask`是Android SDK中的一个类,它为开发者提供了简单的多线程和回调功能。它的核心思想是将长时间...

    Android AsyncTask异步处理下载网页

    Android提供了一种便捷的机制,名为`AsyncTask`,用于在后台线程执行这些任务,同时允许在主线程更新UI。`AsyncTask`是一个轻量级的框架,设计用来简化在Android应用程序中进行后台操作的过程。 `AsyncTask`包含三...

    使用Handler实现异步更新UI例子

    在分析了Handler的工作原理和使用方法后,我们可以看到,异步更新UI的核心是利用了Android的消息传递机制,让主线程与工作线程之间能有效地协同工作。通过Handler,我们可以在不影响UI性能的情况下执行后台任务,...

    Android AsyncTask 异步下载 提高篇

    `AsyncTask`是Android提供的一种轻量级的异步处理机制,特别适用于执行耗时操作,如网络请求、数据库操作或图片下载等。在本教程“Android AsyncTask 异步下载 提高篇”中,我们将深入探讨`AsyncTask`的高级用法和...

    android asynctask的fragment更新UI(附线程管理)

    通过这个例子,我们可以看到在Fragment中使用Android的AsyncTask进行线程管理和UI更新的基本步骤。然而,随着Android版本的更新,推荐使用其他更现代的解决方案,如`LiveData`、`ViewModel`、`Coroutines`或`...

    Android AsyncTask 异步下载基础篇

    `AsyncTask`是Android提供的一种轻量级的异步任务处理框架,特别适用于执行耗时的操作,如网络请求、文件下载或图片加载等。本篇文章将深入讲解如何使用`AsyncTask`进行图片的异步下载。 `AsyncTask`类包含三个泛型...

    Android Handler AsyncTask 异步加载

    AsyncTask是Android提供的一种轻量级的异步执行框架,用于在后台执行计算密集型任务,然后在UI线程中更新结果。它有三个泛型参数,分别代表了输入类型、进度类型和输出类型。AsyncTask提供了`onPreExecute()`(任务...

    Android的AsyncTask异步任务

    本篇文章将深入探讨Android的AsyncTask异步任务,以及如何在实践中应用。 首先,Android是一个基于事件驱动的系统,主线程(UI线程)负责处理用户交互,而复杂的计算或网络请求等耗时操作应在后台线程中执行,以免...

    Android用AsyncTask异步加载图片(新)

    `AsyncTask`是Android提供的一种轻量级的多线程解决方案,它允许开发者在后台执行耗时操作,并在主线程中更新UI,避免了UI阻塞。本篇文章将深入探讨如何在Android中使用`AsyncTask`来异步加载网络图片。 首先,我们...

    Android异步刷新UI多种实现方案

    虽然TimerTask不直接处理UI更新,但可以在任务执行完毕后通过Handler或者直接在主线程调用UI更新方法。这种方式适合实现定时刷新UI的效果,比如定时刷新数据。 对比这三种方法,Asynctask适用于简单快速的任务,且...

    Android开发AsyncTask异步处理任务

    在Android应用开发中,AsyncTask是一个非常重要的工具类,它为开发者提供了在UI线程之外执行耗时操作的能力,从而避免了主线程被阻塞导致的ANR(Application Not Responding)错误。这个博文主要围绕Android开发中的...

    AsyncTask异步加载图片

    在Android开发中,异步加载图片是一个常见的需求,特别是在处理用户界面时,为了提供良好的用户体验,我们需要在后台线程执行耗时操作,如从网络下载图片,然后在UI线程更新视图。`AsyncTask`是Android提供的一个轻...

    Android用AsyncTask异步加载图片

    总结,`Android用AsyncTask异步加载图片`涉及到的关键技术点包括:`AsyncTask`的生命周期、后台线程执行、UI线程更新、图片的网络加载以及进度条的控制。通过合理运用这些技术,可以提高应用的响应速度,提升用户...

    详解android进行异步更新UI的四种方式

    大家都知道由于性能要求,Android要求只能在UI线程中更新UI,要想在其他线程中更新UI,我大致总结了4种方式,欢迎补充纠正: 使用Handler消息传递机制; 使用AsyncTask异步任务; 使用runOnUiThread(action)方法...

    Android AsyncTask(异步) 简单样例

    AsyncTask是Android提供的一个类,它允许开发者在后台线程执行任务,然后在UI线程更新结果,以避免阻塞主线程导致应用无响应(ANR)的情况。它由三个泛型参数定义:Params(输入参数类型),Progress(后台执行过程...

    Android中异步类AsyncTask用法总结

    AsyncTask 是 Android 平台上一种轻量级的异步处理机制,主要用于在后台执行耗时操作,同时确保结果能够在主线程中安全地更新 UI。它简化了多线程编程,尤其是与用户界面交互的需求。 首先,AsyncTask 包含三个泛型...

    AsyncTask 异步多线程加载Demo

    在Android开发中,AsyncTask是一种轻量级的异步任务处理机制,主要用于UI线程与后台线程之间的通信,以实现耗时操作的异步执行,避免阻塞主线程,提高用户体验。`AsyncTask`类提供了简单易用的接口,使得开发者能够...

Global site tag (gtag.js) - Google Analytics