gpt4 book ai didi

java - 在 doInBackground 中创建另一个 AsyncTask

转载 作者:行者123 更新时间:2023-11-29 07:59:01 25 4
gpt4 key购买 nike

我最近浏览了 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 instanceby showing a progress bar in the user interface.

2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is usedto perform background computation that can take a long time. Theparameters of the asynchronous task are passed to this step. Theresult of the computation must be returned by this step and will bepassed back to the last step. This step can also usepublishProgress(Progress...) to publish one or more units of progress.These values are published on the UI thread, in theonProgressUpdate(Progress...) step.

3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution isundefined. This method is used to display any form of progress in theuser interface while the background computation is still executing.For instance, it can be used to animate a progress bar or show logs ina text field.

4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation ispassed 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com