gpt4 book ai didi

android - 我需要管理 Android 异步任务生命周期吗?

转载 作者:太空狗 更新时间:2023-10-29 16:22:03 26 4
gpt4 key购买 nike

我是否需要在 fragment onDestroy 事件中对 asyncTask 调用取消,以防用户点击后退按钮并离开 Activity 时异步任务尚未完成?

如果上一次访问 fragmentActivity 的 asyncTask 仍在运行、尚未完成或尚未取消,我是否还需要检查我的 asyncTask 的现有实例是否仍在运行?

最佳答案

你不必,但你应该。

原因是它一直运行直到它完成,并且从 hive 开始,它甚至只使用一个线程来处理所有 asyncTasks。

无论如何,asyncTask 应该通常用于短时间任务,比如 1-10 秒。这不是规则,但它会帮助您实现存在 asyncTask 的原因 - 能够在后台运行任务。

这里有一些关于 asyncTask from the API 的注释:

"AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask."

API execute() :

"Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use."

如果您无论如何都希望将 asyncTask 用作后台任务,请确认它只有一个实例(不要忘记在不需要时取消它),或者使用 Google 建议避免的下一个代码:

public static <T> void runAsyncTaskInMultipleThreads(final AsyncTask<T,?,?> asyncTask,final T... params)
{
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params);
else asyncTask.execute(params);
}

关于android - 我需要管理 Android 异步任务生命周期吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12063053/

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