首先IntentService是繼承自Service的,那咱們先看看Service的官方介紹,這裏列出兩點比較重要的地方: java
1.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. android
2.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). 面試
稍微翻一下(英文水平通常) express
1.Service不是一個單獨的進程 ,它和應用程序在同一個進程中。 app
2.Service不是一個線程,因此咱們應該避免在Service裏面進行耗時的操做 less
關於第二點我想說下,不知道不少網上的文章都把耗時的操做直接放在Service的onStart方法中,並且沒有強調這樣會出現Application Not Responding!但願個人文章能幫你們認清這個誤區(Service不是一個線程,不能直接處理耗時的操做)。 異步
有人確定會問,那麼爲何我不直接用Thread而要用Service呢?關於這個,你們能夠網上搜搜,這裏不過多解釋。有一點須要強調,若是有耗時操做在Service裏,就必須開啓一個單獨的線程來處理!!!這點必定要銘記在心。 async
IntentService相對於Service來講,有幾個很是有用的優勢,首先咱們看看官方文檔的說明: ide
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests throughstartService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. oop
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
1.Service:
package com.zhf.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class MyService extends Service { @Override public void onCreate() { super.onCreate(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); //經測試,Service裏面是不能進行耗時的操做的,必需要手動開啓一個工做線程來處理耗時操做 System.out.println("onStart"); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("睡眠結束"); } @Override public IBinder onBind(Intent intent) { return null; } }
package com.zhf.service; import android.app.IntentService; import android.content.Intent; public class MyIntentService extends IntentService { public MyIntentService() { super("yyyyyyyyyyy"); } @Override protected void onHandleIntent(Intent intent) { // 經測試,IntentService裏面是能夠進行耗時的操做的 //IntentService使用隊列的方式將請求的Intent加入隊列,而後開啓一個worker thread(線程)來處理隊列中的Intent //對於異步的startService請求,IntentService會處理完成一個以後再處理第二個 System.out.println("onStart"); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("睡眠結束"); } }
測試主程序: