java - 在 doInBackground 中创建另一个 AsyncTask

标签 java android asynchronous android-asynctask

我最近浏览了 SO 以找到答案 to the same question here ,但没有针对这样做的风险问题的答案。但基本上我想在另一个 AsyncTaskdoInBackground() 方法中运行另一个 AsyncTask。这是一种糟糕的方法和/或它是否会留下任何潜在的副作用?

我知道在 onPostExecute() 中运行它是有效的,而且从过去的经验来看,由于 onPostExecute() 运行回来,我没有遇到任何问题在启动 AsyncTask 的主线程上开始。

最佳答案

来自 API 文档:

•The task instance must be created on the UI thread.

doInBackground() 在后台线程上运行。所以你不能从 doInBackground() 创建和运行另一个异步任务。

http://developer.android.com/reference/android/os/AsyncTask .查看线程规则下的主题。

当一个异步任务被执行时,任务会经历 4 个步骤:(直接来自文档)

1.onPreExecute(), invoked on the UI thread before 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.

首次引入时,AsyncTasks 在单个后台线程上连续执行。从 DONUT 开始,这被更改为允许多个任务并行运行的线程池。从 HONEYCOMB 开始,任务在单个线程上执行,以避免并行执行导致的常见应用程序错误。

如果您真的想要并行执行,您可以使用 THREAD_POOL_EXECUTOR 调用 executeOnExecutor(java.util.concurrent.Executor, Object[])。

更新 05-04-2023

AsyncTask 不再用于 android 世界中的异步内容。考虑使用协程。建议尽快切换到协程

https://developer.android.com/kotlin/coroutines?gclid=Cj0KCQjwla-hBhD7ARIsAM9tQKuy9BV88avgYYrrwkcCHJ1zktoctbOrdrWavXT0NTDktIfPdfb8Q-4aAqXIEALw_wcB&gclsrc=aw.ds

Codelab 示例可在 https://developer.android.com/codelabs/kotlin-coroutines#0 获得

关于java - 在 doInBackground 中创建另一个 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15657424/

相关文章:

javascript - 具有内部异步函数的多个同步函数

javascript nodejs if语句以意外顺序调用

java - 如何使用java向手机发送短信警报?

java - System.getenv() 返回 null

java - Android http post 到 ASP.NET Web API 不插入数据

java - 如何在父自定义对象数组列表中获取自定义对象子列表中的单个项目位置?

Android 在自定义 View 中管理配置更改(状态)

java - 在 Java 中处理条形码扫描

java - 使用 Android Studio Facebook SDK

c# - 为什么没有 `DBconnection.CloseAsync()` 而有 `DBconnection.OpenAsync()` ?