Android 处理程序与异步任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2523459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:10:20  来源:igfitidea点击:

Handler vs AsyncTask

android

提问by Steve

I'm confused as to when one would choose AsyncTask over a Handler. Say I have some code I want to run every n seconds which will update the UI. Why would I choose one over the other?

我对何时选择 AsyncTask 而不是 Handler 感到困惑。假设我有一些代码我想每 n 秒运行一次,这将更新 UI。为什么我会选择一个而不是另一个?

采纳答案by Samuh

IMO, AsyncTask was written to provide a convenient, easy-to-use way to achieve background processing in Android apps, without worrying too much about the low-level details(threads, message loops etc). It provides callback methods that help to schedule tasks and also to easily update the UI whenever required.

IMO,编写 AsyncTask 是为了提供一种方便、易于使用的方式来实现 Android 应用程序中的后台处理,而无需过多担心底层细节(线程、消息循环等)。它提供的回调方法有助于安排任务并在需要时轻松更新 UI。

However, it is important to note that when using AsyncTask, a developer is submitting to its limitations, which resulted because of the design decisions that the author of the class took. For e.g. I recently found out that there is a limit to the number of jobs that can be scheduled using AsyncTasks.

但是,重要的是要注意,在使用 AsyncTask 时,开发人员会受到其限制,这是由于类的作者做出的设计决定而导致的。例如,我最近发现可以使用 AsyncTasks 调度的作业数量是有限制的。

Handler is more transparent of the two and probably gives you more freedom; so if you want more control on things you would choose Handler otherwise AsynTask will work just fine.

Handler 在两者中更透明,可能会给你更多的自由;所以如果你想对事情有更多的控制,你会选择 Handler 否则 AsynTask 会工作得很好。

回答by alexanderblom

My rule of thumb would be:

我的经验法则是:

  • If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.

  • If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews(like downloading thumbnails) upon download, use a task queue with Handler.

  • 如果您正在做一些与 UI 相关的独立操作,例如下载数据以显示在列表中,请继续使用AsyncTask.

  • 如果您正在执行多个重复任务,例如下载要在ImageViews下载时显示的多个图像(如下载缩略图),请使用带有Handler.

回答by type-a1pha

Always try to avoid using AsyncTask when possible mainly for the following reasons:

尽可能避免使用 AsyncTask 主要是出于以下原因:

  • AsyncTask is not guaranteed to run since there is a ThreadPool base and max size set by the system and if you create too much asynctask they will eventually be destroyed

  • AsyncTask can be automatically terminated, even when running, depending on the activity lifecycle and you have no control over it

  • AsyncTask methods running on the UI Thread, like onPostExecute, could be executed when the Activity it is referring to, is not visible anymore, or is possibly in a different layout state, like after an orientation change.

  • AsyncTask 不能保证运行,因为系统设置了一个 ThreadPool 基数和最大大小,如果你创建了太多的 asynctask,它们最终会被销毁

  • AsyncTask 可以自动终止,即使在运行时,取决于活动生命周期,您无法控制它

  • 在 UI 线程上运行的 AsyncTask 方法,如 onPostExecute,可以在它所指的 Activity 不再可见时执行,或者可能处于不同的布局状态,例如在方向更改之后。

In conclusion you shouldn't use the UIThread-linked methods of AsyncTask, which is its main advantage!!! Moreover you should only do non critical work on doInBackground. Read this thread for more insights on this problems:

总之,你不应该使用 AsyncTask 的 UIThread 链接方法,这是它的主要优点!!!此外,您应该只在 doInBackground 上做非关键的工作。阅读此线程以获取有关此问题的更多见解:

Is AsyncTask really conceptually flawed or am I just missing something?

AsyncTask 真的在概念上有缺陷还是我只是遗漏了什么?

To conclude try to prefer using IntentServices, HandlerThread or ThreadPoolExecutor instead of AsyncTask when any of the above cited problems ma be a concern for you. Sure it will require more work but your application will be safer.

总而言之,当您可能会担心上述任何问题时,请尝试更喜欢使用 IntentServices、HandlerThread 或 ThreadPoolExecutor 而不是 AsyncTask。当然,它需要更多的工作,但您的应用程序会更安全。

回答by MrSnowflake

If you want to do a calculation every x seconds, you should probably schedule a Runnableon a Handler(with postDelayed()) and that Runnableshould start in the current UI thread. If you want to start it in another thread, use HandlerThread. AsyncTask is easier to use for us but no better than handler.

如果您想每 x 秒进行一次计算,您可能应该RunnableHandler(with postDelayed())上安排 a并且Runnable应该在当前 UI 线程中开始。如果要在另一个线程中启动它,请使用 HandlerThread。AsyncTask 对我们来说更容易使用,但并不比 handler 好。

回答by secretlm

The Handler is associated with the application's main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.

Handler 与应用程序的主线程相关联。它处理和调度从后台线程发送到应用程序主线程的消息和可运行对象。

AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.

AsyncTask 提供了一种简单的方法来处理后台线程,以便更新 UI 而不会因耗时的操作而阻塞它。

The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the MessageQueue in a specific order.

答案是两者都可用于从后台线程更新 UI,不同之处在于您的执行场景。您可以考虑使用处理程序来发布延迟消息或以特定顺序将消息发送到 MessageQueue。

You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.

如果您想以一种简单方便的方式在应用程序主线程和后台线程之间交换参数(从而更新 UI),您可以考虑使用 AsyncTask。

回答by lomza

AsyncTaskpresumes you will do something on the UI thread, after some background work is finished. Also, you can execute it only once(after this, its status is FINISHEDand you'll get an exception trying to execute it once more). Also, the flexibility of using it is not much. Yes, you can use THREAD_POOL_EXECUTORfor a parallel execution, but the effort might be not worthy.

AsyncTask假设你会在一些后台工作完成后在 UI 线程上做一些事情。此外,您只能执行一次(在此之后,它的状态为FINISHED,您将在尝试再次执行时遇到异常)。此外,使用它的灵活性并不大。是的,您可以THREAD_POOL_EXECUTOR用于并行执行,但这种努力可能不值得。

Handlerdoesn't presume anything, except handling Runnables and Messages. Also, it can be run as many times as you wish. You are free to decide to which thread it must be attached to, how it communicates with other handlers, maybe produce them with HandlerThread. So, it's much more flexible and suitable for some repeated work.

Handler除了处理 Runnables 和 Messages 之外,不做任何假设。此外,它可以根据需要运行多次。您可以自由决定它必须附加到哪个线程,它如何与其他处理程序通信,或者使用HandlerThread. 所以,它更灵活,适合一些重复的工作。

Check different kind of Handlerexamples here.

在此处查看不同类型的Handler示例。

回答by Shinoo Goyal

doInBackground- basically does work in another thread. onPostExecute- posts the results on the UI thread and it is internally sending message to handler of main thread. Main UI thread already has a looper and handler associated with it.

doInBackground- 基本上在另一个线程中工作。 onPostExecute- 在 UI 线程上发布结果,并在内部向主线程的处理程序发送消息。主 UI 线程已经有一个与之关联的循环程序和处理程序。

So basically,if you have to do some background task,use AsyncTask. But ultimately,if something needs to be updated on UI,it will be using main thread's handler.

所以基本上,如果您必须执行一些后台任务,请使用 AsyncTask。但最终,如果需要在 UI 上更新某些内容,它将使用主线程的处理程序。

回答by saubhagya das

They are best interview question which is asked. AsyncTask- They are used to offload of UI thread and do tasks in background. Handlers- Android dosent have direct way of communication between UI and background thread. Handlers must be used to send message or runnable through the message queue.

他们是最好的面试问题。 AsyncTask- 它们用于卸载 UI 线程并在后台执行任务。 处理程序- Android 不具有 UI 和后台线程之间的直接通信方式。处理程序必须用于通过消息队列发送消息或可运行。

So AsyncTasks are used where tasks are needed to be executed in background and Handlers are used for communication between a UI and Background Thread.

因此 AsyncTasks 用于需要在后台执行任务的地方,而 Handlers 用于 UI 和后台线程之间的通信。