Android筆記 IntentService與Service的區別,androidintent
Service 在官方API的描述為
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding <service> declaration in its package'sAndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().
Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. More information on this can be found in Processes and Threads. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.
主要用於後台服務 當應用程式被掛到背景時候,為了保證應用某些組件仍然可以工作而引入了Service這個概念,那麼這裡面要強調的是Service不是獨立的進程,也不是獨立的線程,它是依賴於應用程式的主線程的,在更多時候不建議在Service中編寫耗時的邏輯和操作,否則會引起ANR。這時需要引入IntentService,IntentService是繼承Service的,那麼它包含了Service的全部特性,當然也包含service的生命週期,那麼與service不同的是,IntentService在執行onCreate操作的時候,內部開了一個線程,去執行你的耗時操作。
service提供了一個方法 onStartCommand 當service啟動或被調用時候會執行這個方法。
onStartCommand(Intent intent, int flags, int startId)
Called by the system every time a client explicitly starts the service by calling
startService(Intent), providing the arguments it supplied and a unique integer token representing the start request.
IntentService:非同步處理服務,新開一個線程:handlerThread線上程中發訊息,然後接受處理完成後,會清理線程,並且關掉服務。
IntentService有以下特點:
(1) 它建立了一個獨立的背景工作執行緒來處理所有的通過onStartCommand()傳遞給服務的intents。
(2) 建立了一個工作隊列,來逐個發送intent給onHandleIntent()。
(3) 不需要主動調用stopSelft()來結束服務。因為,在所有的intent被處理完後,系統會自動關閉服務。
(4) 預設實現的onBind()返回null
(5) 預設實現的onStartCommand()的目的是將intent插入到工作隊列中