java - 什么是 AsyncTask(或 AsyncResult)以及它通常如何用于 Android?

标签 java android

找不到太多关于这个概念的信息。已经引用过

https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/AsyncResult.java

https://docs.oracle.com/javaee/6/api/javax/ejb/AsyncResult.html

编辑:我相信我所指的 AsyncResult 是为保存通用 asynchronous operation 的结果而选择的特定名称。 。 (后台操作完成后将异步通知用户。)

上面的链接似乎只是这个概念的特定实现。
作为引用,请参阅以下内容:

最佳答案

背景/理论

AsyncTask 允许您在后台线程上运行任务,同时将结果发布到 UI 线程。

The user should always able to interact with the app so it is important to avoid blocking the main (UI) thread with tasks such as downloading content from the web.

This is why we use an AsyncTask.

It offers a straightforward interface by wrapping the UI thread message queue and handler that allow you to send and process runnable objects and messages from other threads.

实现

AsyncTask 是一个泛型类。 (它在其构造函数中采用参数化类型。)

它使用这三种通用类型:

<强> Params - 执行时发送到任务的参数类型。

<强> Progress - 后台计算期间发布的进度单位的类型。

<强> Result - 后台计算结果的类型。

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> { ... }

这三个参数对应于三个主要功能,您可以在AsyncTask中覆盖:

  • doInBackground(Params...)
  • onProgressUpdate(Progress...)
  • onPostExecute(Result)

执行AsyncTask

调用 execute() 带有要发送到后台任务的参数。

发生了什么

  1. 在主/UI 线程上, onPreExecute() 被称为。 (初始化该线程中的某些内容,例如在用户界面上显示进度条。)

  2. 在后台线程上, doInBackground(Params...) 被称为。 (参数是传递给执行函数的参数。)

    • 长时间运行的任务应该发生在哪里

    • 必须至少覆盖 doInBackground()使用AsyncTask。

    • 调用publishProgress(Progress...) 在后台计算仍在执行时更新用户界面中的进度显示。 (例如,为进度条设置动画或在文本字段中显示日志。)

      • 这会导致 onProgressUpdate() 被调用。
  3. 在后台线程上,从doInBackground()返回结果。 。这会触发下一步。

  4. 在主/UI 线程上, onPostExecute() 使用返回的结果进行调用。

示例

再次使用阻塞任务的示例,即从网络下载某些内容,

  • 示例 A 下载图像并将其显示在 ImageView 中,
  • 示例 B 下载一些文件

示例 A

doInBackground()方法下载图像并将其存储在 BitMap 类型的对象中。 onPostExecute()方法获取位图并将其放置在 ImageView 中。

class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bitImage;

    public DownloadImageTask(ImageView bitImage) {
        this.bitImage = bitImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mBmp = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mBmp = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mBmp;
    }

    protected void onPostExecute(Bitmap result) {
        bitImage.setImageBitmap(result);
    }
}

示例 B

 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));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

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

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

示例 B 执行

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

关于java - 什么是 AsyncTask(或 AsyncResult)以及它通常如何用于 Android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31277518/

相关文章:

java - Selenium 文档 - 如何使用?

java - 如何按顺序播放声音?

java - Android HttpURLConnection 始终未经授权的 401 响应(Spring Boot REST API)

android - 如何使用 MediaRecorder 获取每个录音频率?

android - 上载图片时,ProgressDialog不显示

java - 链接生成

java - Webclient 发送没有正文的 POST 将得到 IllegalStateException

java - AKKA 在一段时间后停止记录堆栈跟踪

android - Android onResume后ListView为空

android - 从 Activity 向上导航回到 fragment