何时使用 Service、AsyncTask 或 Handler?

发布于 2024-08-22 03:55:10 字数 37 浏览 6 评论 0原文

有人能告诉我真正的区别吗?

Can someone tell me the TRUE difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

笑饮青盏花 2024-08-29 03:55:10

我的经验法则是,AsyncTask 适用于当我想做与单个 Activity 相关的事情时,而 Service 适用于当我想做的事情时做一些在启动它的活动在后台后继续进行的事情。

因此,如果我想在 Activity 中进行少量后台处理而不占用 UI,我将使用 AsyncTask。然后,我将使用该 Activity 中的默认 Handler 来传回消息,以确保更新发生在主线程上。在主线程上处理更新有两个好处:UI 更新正确发生,并且您不必太担心同步问题。

例如,如果我想要进行下载,这可能需要一段时间,我会使用服务。因此,如果我转到应用程序中的另一个 Activity 或完全另一个应用程序,我的 Service 可以继续运行并继续下载文件,这样当我返回到我的应用程序时它就准备好了。在这种情况下,我可能会使用 状态栏通知< /a> 下载完成后,用户可以选择在方便的时候返回我的应用程序。

如果您将 AsyncTask 用于长时间运行的进程,您会发现,在您离开 Activity 后,它可能会继续运行,但是:

  • 如果 Activity处理完成后, 位于后台,当您尝试使用结果等更新 UI 时,您可能会遇到问题。
  • 后台 Activity 更有可能被 Android 杀死。比服务需要内存。

My rule of thumb is that an AsyncTask is for when I want to do something tied to single Activity and a Service is for when I want to do something that will carry on after the Activity which started it is in the background.

So if I want to do a small bit of background processing in the Activity without tying up the UI I'll use an AsyncTask. I'll then use the default Handler from that Activity to pass messages back to ensure updates happen on the main thread. Processing the updates on the main thread has two benefits: UI updates happen correctly and you don't have to worry so much about synchronisation problems.

If for example, I wanted to do a download which might take a while I'd use a Service. So if I went to another Activity in my application or another application entirely my Service could keep running and keep downloading the file so it would be ready when I returned to my application. In this case I'd probably use a Status Bar Notification once the download was complete, so the user could choose to return to my application whenever was convenient for them.

What you'll find if you use an AsyncTask for a long-running process it may continue after you've navigated away from the Activity but:

  • If the Activity is in the background when your processing is complete you may have problems when you try to update the UI with the results etc.
  • A background Activity is far more likely to be killed by Android when it needs memory than a Service.
允世 2024-08-29 03:55:10

当您需要在后台长时间运行某些内容时,请使用服务。它不受任何活动的约束。典型的例子是音乐播放器。
当当前活动中必须在后台完成某些操作时,AsyncTask 非常有用。例如下载、搜索文件内的文本等
就我个人而言,我仅使用处理程序来将更改发布到 UI 线程。例如,您在后台线程中进行一些计算并通过处理程序发布结果。

底线:在大多数情况下,AsyncTask 就是您所需要的。

Use Service when you've got something that has to be running in the background for extended periods of time. It's not bound to any activity. The canonical example is a music player.
AsyncTask is great when some stuff has to be done in background while in the current activity. E.g. downloading, searching for text inside a file, etc.
Personally I use Handlers only to post changes to the UI thread. E.g. you do some computations in a background thread and post the result via handler.

The bottom line: in most cases, AsyncTask is what you need.

╭⌒浅淡时光〆 2024-08-29 03:55:10

为了补充此处有关服务和 AsyncTask 之间区别的其他答案,还值得注意[0]:

  • 服务不是一个单独的进程。 Service 对象本身并不意味着它运行在自己的进程中;除非另有说明,否则它与其所属的应用程序在同一进程中运行。
  • 服务不是线程。它本身并不是一种在主线程之外完成工作的方法(以避免应用程序无响应错误)。

服务往往是描述应用程序重要部分的东西,而不是通常有助于 Activity 和/或提高 UI 响应能力的 AsyncTask。除了提高代码清晰度之外,服务还可以与其他应用程序共享,从而在您的应用程序和外部世界之间提供清晰的接口。

我想说的是,开发者指南里有很多很好的答案,而不是一本书。

[0]来源:http://developer.android.com/reference/android/app/Service .html#WhatIsAService

To complement the other answers here regarding the distinction between service and AsyncTask, it is also worth noting[0]:

  • A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
  • A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Services tend to be things that describes a significant part of your application - rather than an AsyncTask which is typically contributes to an Activity and/or improves UI responsiveness. As well as improving code clarity Services can also be shared with other applications, providing clear interfaces between your app and the outside world.

Rather than a book I would say the developer guide has lots of good answers.

[0] Source: http://developer.android.com/reference/android/app/Service.html#WhatIsAService

傾旎 2024-08-29 03:55:10
  • AsyncTask: 当我希望在不挂起 UI 的情况下执行某些操作时反映 UI 中的变化。

例如:通过单击按钮下载某些内容,并保持在同一活动中显示进度条/搜索栏以更新下载的百分比。如果Activity进入后台,就有可能发生冲突。

  • 服务:当我希望在后台执行某些不需要更新 UI 的操作时,请使用服务。它不关心应用程序是在前台还是后台。

例如:当从 Android Market 下载的任何应用程序在状态栏中显示通知时, UI 返回上一页让你做其他事情。

  • AsyncTask: When I wish to do something without hanging the UI & reflect the changes in the UI.

E.g.: Downloading something on Button Click, remaining in the same activity & showing progress bar/seekbar to update the percentage downloaded. If the Activity enters the background, there are chances of conflict.

  • Service: When I wish to do something in the background that doesn’t need to update the UI, use a Service. It doesn’t care whether the Application is in the foreground or background.

E.g.: When any app downloaded from Android Market shows notification in the Status Bar & the UI returns to the previous page & lets you do other things.

顾挽 2024-08-29 03:55:10

服务

服务是一个应用程序组件,可以在后台执行长时间运行的操作,并且不提供用户界面。另一个应用程序组件可以启动一个服务,即使用户切换到另一个应用程序,它也会继续在后台运行。此外,组件可以绑定到服务以进行交互。

何时使用?

没有 UI 的任务,但不应太长。在服务中使用线程来执行长任务。
任务总体较长。

触发器: 调用方法 onStartService()

触发自: 任何线程

运行于: 其托管进程的主线程。该服务不会创建自己的线程,也不会在单独的进程中运行(除非您另外指定)

限制/缺点: 可能会阻塞主线程


AsyncTask

AsyncTask 可以正确且轻松地使用 UI 线程。此类允许在 UI 线程上执行后台操作并发布结果,而无需操作线程和/或处理程序。异步任务由在后台线程上运行的计算定义,其结果在 UI 线程上发布。

何时使用?

必须与主线程通信的小任务
对于并行任务,请使用多个实例或执行器
可能需要几毫秒以上的磁盘绑定任务

触发器: 调用方法execute()

触发自: 主线程

运行于: Worker线。但是,可以在两者之间调用主线程方法来发布进度。

限制/缺点:

  • 一个实例只能执行一次(因此不能循环运行)
  • 必须从主线程创建和执行

参考链接

Service

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with.

When to use?

Task with no UI, but shouldn’t be too long. Use threads within service for long tasks.
Long task in general.

Trigger: Call to method onStartService()

Triggered from: Any Thread

Runs on: Main thread of its hosting process. The service does not create its own thread and does not run in a separate process (unless you specify otherwise)

Limitations / Drawbacks: May block main thread


AsyncTask

AsyncTask enables the proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

When to use?

Small task having to communicate with main thread
For tasks in parallel use multiple instances OR Executor
Disk-bound tasks that might take more than a few milliseconds

Trigger: Call to method execute()

Triggered from: Main Thread

Runs on: Worker thread. However, Main thread methods may be invoked in between to publish progress.

Limitations / Drawbacks:

  • One instance can only be executed once (hence cannot run in a loop)
  • Must be created and executed from the Main thread

Ref Link

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文