IntentService是繼承並處理異步請求的一個類,在IntentService內有一個工作線程來處理耗時操作,啟動IntentService的方式和啟動傳統的Service一樣,同時,當任務執行完后,IntentService會自動停止,而不需要我們手動去控制或stopSelf()。另外,可以啟動IntentService多次,而每一個耗時操作會以工作隊列的方式在IntentService的onHandleIntent回調方法中執行,並且,每次只會執行一個工作線程,執行完第一個再執行第二個,以此類推。
先來看一下IntentService類的源碼:
public void onCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock. super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); //開啟一個工作線程 mServiceLooper = thread.getLooper(); //單獨的消息隊列 mServiceHandler = new ServiceHandler(mServiceLooper); }
定義一個IntentService的子類:
public class MIntentService extends IntentService { public MIntentService(){ super("MIntentService"); } /** * Creates an IntentService. Invoked by your subclass's constructor. * @param name Used to name the worker thread, important only for debugging. */ public MIntentService(String name) { super(name); } @Override public void onCreate() { Log.e("MIntentService--", "onCreate"); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e("MIntentService--", "onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override protected void onHandleIntent(Intent intent) { Log.e("MIntentService--", Thread.currentThread().getName() + "--" + intent.getStringExtra("info") ); for(int i = 0; i < 100; i++){ //耗時操作 Log.i("onHandleIntent--", i + "--" + Thread.currentThread().getName()); } } @Override public void onDestroy() { Log.e("MIntentService--", "onDestroy"); super.onDestroy(); } }
開啟IntentService服務:
public void intentClick(View v){ Intent intent = new Intent(this, MIntentService.class); intent.putExtra("info", "good good study"); startService(intent); }
點擊按鈕之后輸出結果為(過濾log.e):
10-25 16:54:58.852 27135-27135/com.example.lenovo.myintentservicedemo E/MIntentService--﹕ onCreate
10-25 16:54:58.852 27135-27135/com.example.lenovo.myintentservicedemo E/MIntentService--﹕ onStartCommand
10-25 16:54:58.856 27135-27354/com.example.lenovo.myintentservicedemo E/MIntentService--﹕ IntentService[MIntentService]--good good study
10-25 16:54:58.879 27135-27135/com.example.lenovo.myintentservicedemo E/MIntentService--﹕ onDestroy
Intent服務開啟后,執行完onHandleIntent里面的任務就自動銷毀結束,通過打印的線程名稱可以發現是新開了一個線程來處理耗時操作的,即是耗時操作也可以被這個線程管理和執行,同時不會產生ANR的情況。