IntentService的介紹與使用

在介紹IntentService之前,我們都知道不管是何種service都是運行在UI線程中的。我們先要知道service,畢竟IntentService是繼承Service的。首先,service一般是使用在我們需要應(yīng)用在后臺時做一些操作。這里就不詳細介紹service的用法了。

既然service是完成后臺操作,總避免不了處理一些耗時的操作,處理耗時操作在service中只能使用最常規(guī)的方法就是開一個線程(new Thread())進行處理,如果有多個操作,還有開啟多個子線程或者在一個子線程中同步進行調(diào)用。基于這個場景我們先來介紹下IntentService。

IntentService:異步處理服務(wù),新開一個線程:handlerThread在線程中發(fā)消息,然后接受處理完成后,會清理線程,并且關(guān)掉服務(wù)。

IntentService有以下特點:

(1) 它創(chuàng)建了一個獨立的工作線程來處理所有的通過onStartCommand()傳遞給服務(wù)的intents。

(2) 創(chuàng)建了一個工作隊列,來逐個發(fā)送intent給onHandleIntent()。

(3) 不需要主動調(diào)用stopSelft()來結(jié)束服務(wù)。因為,在所有的intent被處理完后,系統(tǒng)會自動關(guān)閉服務(wù)。

(4) 默認實現(xiàn)的onBind()返回null

(5) 默認實現(xiàn)的onStartCommand()的目的是將intent插入到工作隊列中

public class IntentServiceDemo extends IntentService {

public IntentServiceDemo() {  
    //必須實現(xiàn)父類的構(gòu)造方法  
    super("IntentServiceDemo");  
}  

//提供了一個onBind()方法的默認實現(xiàn),它返回null
@Override  
public IBinder onBind(Intent intent) {  
    System.out.println("onBind");  
    return super.onBind(intent);  
}  


@Override  
public void onCreate() {  
    System.out.println("onCreate");  
    super.onCreate();  
}  

@Override  
public void onStart(Intent intent, int startId) {  
    System.out.println("onStart");  
    super.onStart(intent, startId);  
}  

//生成一個默認的且與主線程互相獨立的工作者線程來執(zhí)行所有傳送至 onStartCommand()的Intent。將intent先傳送至    工作隊列(onHandleIntent生成的)),然后從工作隊列中每次去出一個intent傳送給onHandleIntent進行處理。
@Override  
public int onStartCommand(Intent intent, int flags, int startId) {  
    System.out.println("onStartCommand");  
    return super.onStartCommand(intent, flags, startId);  
}  


@Override  
public void setIntentRedelivery(boolean enabled) {  
    super.setIntentRedelivery(enabled);  
    System.out.println("setIntentRedelivery");  
}  

//生成一個工作隊列來傳送Intent對象給你的onHandleIntent()方法,同一時刻只傳送一個Intent對象,這樣一來,不必 //擔心多線程的問題。
@Override
protected void onHandleIntent(Intent intent) {
//Intent是從Activity發(fā)過來的,攜帶識別參數(shù),根據(jù)參數(shù)不同執(zhí)行不同的任務(wù)
String action = intent.getExtras().getString("param");
if (action.equals("oper1")) {
System.out.println("Operation1");
}else if (action.equals("oper2")) {
System.out.println("Operation2");
}

    try {  
        Thread.sleep(2000);  
    } catch (InterruptedException e) {  
        e.printStackTrace();  
    }  
}  

@Override  
public void onDestroy() {  
    System.out.println("onDestroy");  
    super.onDestroy();  
}  

}

//開啟IntentService的方式跟service是一樣的startService(intent);這個intent在onStartCommand中接收,然后生成一個工作隊列來傳送給onHandleIntent來進行處理,同一線程只能傳送一個intent的

//IntentService還有一個stopSelf()方法:在所有的請求(Intent)都被執(zhí)行完以后會自動停止服務(wù),所以,你不需要自己去調(diào)用stopSelf()方法來停止該服務(wù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容