android中的service,intentService和有什么不一样? [英] What is the difference between service, intentService in android?
问题描述
Service
和Android中的IntentService
有什么区别?
What is the difference between Service
and an IntentService
in Android?
AsyncTask
和Android中的IntentService
有什么区别?
What is the difference between AsyncTask
and an IntentService
in Android?
推荐答案
1. Service和IntentService之间的区别
服务:它是Android服务的基类,可以扩展以创建任何服务. 由于该服务在UI线程中运行,因此需要您创建一个工作线程来执行其工作.
Service: It is the base class for the Android services, that you can extend for creating any service. Since the service run inside the UI thread, it requires that you create a working thread for executing its work.
IntentService :它是Service
的子类,可简化您的工作.它已经在工作线程中工作,并且可以接收异步请求.因此,您无需手动创建它,也不必担心同步.您可以简单地扩展它并覆盖方法:
IntentService: it is a subclass of Service
, that simplifies your work. It works already in a working thread, and can receive asynchronous requests. So, you don't need to create it manually, or to worry about synchronization. You can simply extend it and override the method:
onHandleIntent(Intent intent)
您可以在其中管理所有传入请求.
where you can manage all the incoming requests.
看看文档,您可以看到详细信息IntentService
为您做什么:
Taking a look at the documentation, you can see in details what the IntentService
do for you:
- 创建一个默认工作线程,该线程执行与应用程序主线程分开的所有传递给
onStartCommand()
的意图. - 创建一个工作队列,一次将一个意图传递给您的
onHandleIntent()
实现,因此您不必担心多线程. - 在处理所有启动请求后停止服务,因此您不必调用
stopSelf()
. - 提供
onBind()
的默认实现,该实现返回null. - 提供
onStartCommand()
的默认实现,该默认实现将意图发送到工作队列,然后发送到您的onHandleIntent()
实现.
- Creates a default worker thread that executes all intents delivered to
onStartCommand()
separate from your application's main thread. - Creates a work queue that passes one intent at a time to your
onHandleIntent()
implementation, so you never have to worry about multi-threading. - Stops the service after all start requests have been handled, so you never have to call
stopSelf()
. - Provides default implementation of
onBind()
that returns null. - Provides a default implementation of
onStartCommand()
that sends the intent to the work queue and then to youronHandleIntent()
implementation.
因此,如果您需要更多控制权,则可以使用Service
类,但是对于简单服务而言,最好的解决方案通常是IntentService
.
So, if you need more control you can use the Service
class, but often for a simple service the best solution is the IntentService
.
2. AsyncTask和Service之间的区别
它们是两个不同的概念.
They are two different concepts.
服务:可以用作没有界面的活动.适合长时间运行的操作.
Service: can be intended as an Activity with no interface. It is suitable for long-running operations.
AsyncTask:是一个特殊的类,它包装了一个工作线程(执行后台操作),从而促进了与UI线程的交互,而无需直接管理线程或处理程序.
AsyncTask: is a particular class that wraps a working thread (performing background operations), facilitating the interaction with the UI Thread, without managing threads or handlers directly.
这篇关于android中的service,intentService和有什么不一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!