ContextWrapper -> Service 位于 android.app 包中 Service的生命周期 Service啟動(dòng) 1.StartService 同一個(gè)Service Start多次,onCreate()執(zhí)..."/>
溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android基礎(chǔ)(五) – Service生命周期及啟動(dòng)方式

發(fā)布時(shí)間:2020-07-05 16:34:58 來源:網(wǎng)絡(luò) 閱讀:462 作者:lm8751 欄目:移動(dòng)開發(fā)

繼承關(guān)系

Context -> ContextWrapper -> Service 位于 android.app 包中

Service的生命周期

Service啟動(dòng)

1.StartService 同一個(gè)Service Start多次,onCreate()執(zhí)行一次,onStartCommand()執(zhí)行多次

2.BindService 同一個(gè)Service bind多次, onCreate()執(zhí)行一次,onBind()也執(zhí)行一次

注意:

1.啟動(dòng)也分隱式和顯式.但考慮到安全等因數(shù),如果不是也許需求 一般我們使用顯示的調(diào)用方式。

2.onStartCommand(Intent intent, int flags, int startId)

onStartCommand有4種返回值

START_STICKY:如果service進(jìn)程被kill掉,保留service的狀態(tài)為開始狀態(tài),但不保留遞送的intent對(duì)象。隨后系統(tǒng)會(huì)嘗試重新創(chuàng)建service,由于服務(wù)狀態(tài)為開始狀態(tài),所以創(chuàng)建服務(wù)后一定會(huì)調(diào)用onStartCommand(Intent,int,int)方法。如果在此期間沒有任何啟動(dòng)命令被傳遞到service,那么參數(shù)Intent將為null。

START_NOT_STICKY:“非粘性的”。使用這個(gè)返回值時(shí),如果在執(zhí)行完onStartCommand后,服務(wù)被異常kill掉,系統(tǒng)不會(huì)自動(dòng)重啟該服務(wù)。

START_REDELIVER_INTENT:重傳Intent。使用這個(gè)返回值時(shí),如果在執(zhí)行完onStartCommand后,服務(wù)被異常kill掉,系統(tǒng)會(huì)自動(dòng)重啟該服務(wù),并將Intent的值傳入。

START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保證服務(wù)被kill后一定能重啟。

3.BindService例代碼

Service部分

private BindServiceX myBinderServiceX=new BindServiceX();
public class BindServiceX extends Binder{
public BindService getBindService() {
return BindService.this;
}
}

@Override
public IBinder onBind(Intent arg0) {
    // 此處返回自定義Binder
    return myBinderServiceX;
}

組件調(diào)用部分(以Activity為例)

Intent intentBind = new Intent(AndroidServiceActivity.this, BindService.class);
bindService(intentBind,
new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        //Service對(duì)外提供Bind
       BindServiceX bindServiceX = (BindServiceX) service;
       //通過bind提供的方法得到Service引用
       BindService bindService = bindServiceX.getBindService();
       //todo 接下來可以和Service通信了

    }
};

, Context.BIND_AUTO_CREATE);

Service關(guān)閉

1.stopSelf();

2.stopSelfResult();

3.stopService()

注意:

1.同時(shí)使用 startService 與 bindService 要注意到,Service 的終止,需要unbindService與stopService同時(shí)調(diào)用(調(diào)用順序無所謂),才能終止 Service.

2.Service哪種方式啟動(dòng)必須調(diào)用與之對(duì)應(yīng)方法才會(huì)關(guān)閉Service。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI