java 何时使用 Service、AsyncTask 或 Handler?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2285680/
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
When to use a Service or AsyncTask or Handler?
提问by TIMEX
Can someone tell me the TRUEdifference?
有人能告诉我真正的区别吗?
回答by Dave Webb
My rule of thumb is that an AsyncTaskis for when I want to do something tied to single Activityand a Serviceis for when I want to do something that will carry on after the Activity which started it is in the background.
我的经验法则是,anAsyncTask是当我想做一些与单身相关的事情时,Activity而 aService是当我想做一些在启动它的 Activity 在后台后继续进行的事情时。
So if I want to do a small bit of background processing in the Activitywithout tying up the UI I'll use an AsyncTask. I'll then use the default Handlerfrom that Activityto 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.
因此,如果我想在Activity不绑定 UI的情况下进行少量后台处理,我将使用AsyncTask. 然后我会使用默认Handler从Activity传回的消息,以确保更新发生在主线程。在主线程上处理更新有两个好处:UI 更新正确发生,您不必太担心同步问题。
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 Activityin my application or another application entirely my Servicecould 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 Notificationonce the download was complete, so the user could choose to return to my application whenever was convenient for them.
例如,如果我想做一个可能需要一段时间的下载,我会使用Service. 因此,如果我转到Activity我的应用程序中的另一个或另一个应用程序,我Service可以继续运行并继续下载文件,以便在我返回到我的应用程序时准备就绪。在这种情况下,我可能会在下载完成后使用状态栏通知,这样用户就可以选择在他们方便的时候返回我的应用程序。
What you'll find if you use an AsyncTaskfor a long-running process it may continue after you've navigated away from the Activitybut:
如果您将 anAsyncTask用于长时间运行的过程,您会发现它在您离开Activity但是后可能会继续:
- If the
Activityis 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
Activityis far more likely to be killed by Android when it needs memory than aService.
- 如果
Activity处理完成时 处于后台,则在尝试使用结果等更新 UI 时可能会遇到问题。 Activity当需要内存时,背景比Service.
回答by yanchenko
Use Servicewhen 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.
AsyncTaskis 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 Handlersonly to post changes to the UI thread. E.g. you do some computations in a background thread and post the result via handler.
当您的某些内容必须在后台长时间运行时,请使用Service。它不受任何活动的约束。典型的例子是音乐播放器。当在当前活动中必须在后台完成某些事情时,
AsyncTask非常有用。例如下载、在文件中搜索文本等。
我个人只使用处理程序将更改发布到 UI 线程。例如,您在后台线程中进行一些计算并通过处理程序发布结果。
The bottom line: in most cases, AsyncTaskis what you need.
底线:在大多数情况下,AsyncTask正是您所需要的。
回答by Uniqe
To complement the other answers here regarding the distinction between service and AsyncTask, it is also worth noting[0]:
为了补充这里关于 service 和 AsyncTask 之间区别的其他答案,还值得注意[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).
- 服务不是一个单独的过程。Service 对象本身并不意味着它在自己的进程中运行;除非另有说明,否则它会在与其所属的应用程序相同的进程中运行。
- 服务不是线程。它本身并不是在主线程之外进行工作的一种方式(以避免应用程序无响应错误)。
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.
服务往往是描述应用程序重要部分的事物 - 而不是通常有助于活动和/或提高 UI 响应能力的 AsyncTask。除了提高代码清晰度外,服务还可以与其他应用程序共享,为您的应用程序与外界提供清晰的接口。
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
[0] 来源:http: //developer.android.com/reference/android/app/Service.html#WhatIsAService
回答by Nital
- AsyncTask:When I wish to do something without hanging the UI & reflect the changes in the UI.
- AsyncTask:当我希望在不挂起 UI 的情况下做某事并反映 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.
例如:在 Button Click 上下载一些东西,保持在相同的活动中并显示进度条/搜索栏以更新下载的百分比。如果 Activity 进入后台,则有可能发生冲突。
- 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.
- 服务:当我希望在后台做一些不需要更新 UI 的事情时,请使用服务。它不关心应用程序是在前台还是后台。
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.
例如:当从 Android Market 下载的任何应用程序在状态栏中显示通知时,UI 将返回上一页并让您做其他事情。
回答by akhilesh0707
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.
Service 是一个应用程序组件,可以在后台执行长时间运行的操作,并且不提供用户界面。另一个应用程序组件可以启动一个服务,即使用户切换到另一个应用程序,它也会继续在后台运行。此外,组件可以绑定到服务进行交互。
When to use?
什么时候使用?
Task with no UI, but shouldn't be too long. Use threads within service for long tasks. Long task in general.
没有 UI 的任务,但不应太长。将服务中的线程用于长任务。一般任务时间长。
Trigger:Call to method onStartService()
触发器:调用方法 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.
AsyncTask 可以正确且轻松地使用 UI 线程。此类允许在 UI 线程上执行后台操作和发布结果,而无需操作线程和/或处理程序。异步任务由在后台线程上运行且其结果发布在 UI 线程上的计算定义。
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()
触发器:调用方法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
参考链接

