IntentService是繼承并處理異步請(qǐng)求的一個(gè)類社牲,在IntentService內(nèi)有一個(gè)工作線程來處理耗時(shí)操作搏恤,啟動(dòng)IntentService的方式和啟動(dòng)傳統(tǒng)的Service一樣湃交,同時(shí),當(dāng)任務(wù)執(zhí)行完后痛阻,IntentService會(huì)自動(dòng)停止腮敌,而不需要我們手動(dòng)去控制或stopSelf()糜工。另外,可以啟動(dòng)IntentService多次油坝,而每一個(gè)耗時(shí)操作會(huì)以工作隊(duì)列的方式在IntentService的onHandleIntent回調(diào)方法中執(zhí)行刨裆,并且,每次只會(huì)執(zhí)行一個(gè)工作線程瞬女,執(zhí)行完第一個(gè)再執(zhí)行第二個(gè)努潘,以此類推。
先來看一下IntentService類的源碼:
publicvoid 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 =newHandlerThread("IntentService[" + mName + "]");
? ? ? ? thread.start(); //開啟一個(gè)工作線程? ? ? ? mServiceLooper = thread.getLooper();//單獨(dú)的消息隊(duì)列mServiceHandler =new ServiceHandler(mServiceLooper);
}
定義一個(gè)IntentService的子類:
publicclassMIntentServiceextends 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
? ? publicvoid onCreate() {
? ? ? ? Log.e("MIntentService--", "onCreate");
? ? ? ? super.onCreate();
? ? }
? ? @Override
? ? publicintonStartCommand(Intent intent,intflags,int startId) {
? ? ? ? Log.e("MIntentService--", "onStartCommand");
? ? ? ? returnsuper.onStartCommand(intent, flags, startId);
? ? }
? ? @Override
? ? protectedvoid onHandleIntent(Intent intent) {
? ? ? ? Log.e("MIntentService--", Thread.currentThread().getName() + "--" + intent.getStringExtra("info") );
? ? ? ? for(inti = 0; i < 100; i++){//耗時(shí)操作Log.i("onHandleIntent--",? i + "--" + Thread.currentThread().getName());
? ? ? ? }
? ? }
? ? @Override
? ? publicvoid onDestroy() {
? ? ? ? Log.e("MIntentService--", "onDestroy");
? ? ? ? super.onDestroy();
? ? }
}
開啟IntentService服務(wù):
publicvoid intentClick(View v){
? ? ? ? Intent intent =newIntent(this, MIntentService.class);
? ? ? ? intent.putExtra("info", "good good study");
? ? ? ? startService(intent);
}
點(diǎn)擊按鈕之后輸出結(jié)果為(過濾log.e):
10-25 16:54:58.852? 27135-27135/com.example.lenovo.myintentservicedemo E/MIntentService--﹕ onCreate10-25 16:54:58.852? 27135-27135/com.example.lenovo.myintentservicedemo E/MIntentService--﹕ onStartCommand10-25 16:54:58.856? 27135-27354/com.example.lenovo.myintentservicedemo E/MIntentService--﹕IntentService[MIntentService]--good good study10-25 16:54:58.879? 27135-27135/com.example.lenovo.myintentservicedemo E/MIntentService--﹕ onDestroy
Intent服務(wù)開啟后压怠,執(zhí)行完onHandleIntent里面的任務(wù)就自動(dòng)銷毀結(jié)束,通過打印的線程名稱可以發(fā)現(xiàn)是新開了一個(gè)線程來處理耗時(shí)操作的蜗顽,即是耗時(shí)操作也可以被這個(gè)線程管理和執(zhí)行,同時(shí)不會(huì)產(chǎn)生ANR的情況羽利。