何时使用 Service、AsyncTask 或 Handler?
有人能告诉我真正的区别吗?
Can someone tell me the TRUE difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有人能告诉我真正的区别吗?
Can someone tell me the TRUE difference?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
我的经验法则是,
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 singleActivity
and aService
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 anAsyncTask
. I'll then use the defaultHandler
from thatActivity
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 anotherActivity
in my application or another application entirely myService
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 theActivity
but: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.Activity
is far more likely to be killed by Android when it needs memory than aService
.当您需要在后台长时间运行某些内容时,请使用服务。它不受任何活动的约束。典型的例子是音乐播放器。
当当前活动中必须在后台完成某些操作时,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.
为了补充此处有关服务和 AsyncTask 之间区别的其他答案,还值得注意[0]:
服务往往是描述应用程序重要部分的东西,而不是通常有助于 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]:
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
例如:通过单击按钮下载某些内容,并保持在同一活动中显示进度条/搜索栏以更新下载的百分比。如果Activity进入后台,就有可能发生冲突。
例如:当从 Android Market 下载的任何应用程序在状态栏中显示通知时, 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.
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.
服务
服务是一个应用程序组件,可以在后台执行长时间运行的操作,并且不提供用户界面。另一个应用程序组件可以启动一个服务,即使用户切换到另一个应用程序,它也会继续在后台运行。此外,组件可以绑定到服务以进行交互。
何时使用?
没有 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:
Ref Link