Android Service

Service,能成為Android四大組件之一,它的重要性就不言而喻了。

先說要講什么:

  • Service的使用
  • Service的生命周期
  • Service運行在什么線程
  • 對Service的理解

Service的使用

作為四大組件之一,使用前肯定需要在AndroidManifest.xml中注冊。

<service android:name=".service.MyIntentService" />
<service android:name=".service.NormalService" />

創(chuàng)建類并繼承android.app.Service

public class NormalService extends Service {

    final String TAG = "Service";

    MyBinder myBinder = new MyBinder();

    @Override
    public void onCreate() {
        super.onCreate();

        LogTool.e(TAG, "Service Thread --> " + Thread.currentThread().getName());
        LogTool.e(TAG, "----- onCreate -----");
    }

    @Override
    public void onDestroy() {
        LogTool.e(TAG, "----- onDestroy -----");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogTool.e(TAG, "----- onStartCommand -----");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onRebind(Intent intent) {
        LogTool.e(TAG, "----- onRebind -----");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogTool.e(TAG, "----- onUnbind -----");
        return super.onUnbind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        LogTool.e(TAG, "----- onBind -----");
        return myBinder;
    }

    class MyBinder extends Binder {

        public void doSth() {
            LogTool.e(TAG, "-----Binder  doSth -----");
            LogTool.e(TAG, "Binder Thread --> " + Thread.currentThread().getName());
        }
    }
}

沒有復(fù)雜的邏輯,基本上是繼承父類方法,然后打印相應(yīng)log。

兩種方式使用Service:

//啟動一個Service
Intent intent = new Intent(this, NormalService.class);
startService(intent);
//停止一個Service
Intent intent = new Intent(this, NormalService.class);
stopService(intent);
//以“綁定”的方式啟動一個Service
//mServiceConnection對象稍后再談
Intent intent = new Intent(this, NormalService.class);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
//解除綁定
unbindService(mServiceConnection);

Service的生命周期

先不看線程信息,通過startService開啟一個服務(wù),它的生命周期是這樣的:

 E/Service: ----- onCreate -----
 E/Service: ----- onStartCommand -----

這時,一個服務(wù)已經(jīng)創(chuàng)建了。如果再次執(zhí)行startService,開啟同一個服務(wù),onStartCommand方法被再次調(diào)用,而onCreate只在Service第一次被創(chuàng)建時調(diào)用。

E/Service: ----- onStartCommand -----

通過stopService結(jié)束一個服務(wù)

E/Service: ----- onDestroy -----

通過bindService開啟一個服務(wù)

bindService(intent, mServiceConnection, BIND_AUTO_CREATE);

mServiceConnection是用來維護Activity與Service之間的聯(lián)系。

ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        LogTool.e(TAG, "----- onServiceConnected -----");
        myBinder = (NormalService.MyBinder) service;
        myBinder.doSth();
    }
    @Override
    public void onServiceDisconnected(ComponentName name) {
        LogTool.e(TAG, "----- onServiceDisconnected -----");
    }
};

綁定是異步的,IBinder對象只能從onServiceConnected方法中獲得。
BIND_AUTO_CREATE是最常用的flag,它表示在service不存在時就創(chuàng)建一個,還有其他幾種標識可供選擇。通過bindService開啟一個Service,它的生命周期是這樣的:

E/Service: ----- onCreate -----
E/Service: ----- onBind -----
E/Service: ----- onServiceConnected -----

Service創(chuàng)建后,再次bindService

E/Service: ----- onBind -----

解除綁定或者綁定的activity返回

E/Service: ----- onUnbind -----
E/Service: ----- onDestroy -----

如果兩種啟動Service的方式同時用,會有什么效果呢?

startService --> bindService --> stopService --> unbindService

//startService 
E/Service: ----- onCreate -----
E/Service: ----- onStartCommand -----
//bindService
E/Service: ----- onBind -----
E/Service: ----- onServiceConnected -----
//stopService什么也沒打印
//unbindService
E/Service: ----- onUnbind -----
E/Service: ----- onDestroy -----

startService --> bindService -->unbindService --> stopService

//startService 
E/Service: ----- onCreate -----
E/Service: ----- onStartCommand -----
//bindService
E/Service: ----- onBind -----
E/Service: ----- onServiceConnected -----
//unbindService
E/Service: ----- onUnbind -----
//stopService
E/Service: ----- onDestroy -----

startService和bindService的先后順序不影響最終結(jié)果。

把Service看做一個對象,startService和bindService就好比這個對象的兩個強引用,onDestroy是系統(tǒng)回收Service對象內(nèi)存的操作,onUnbind是bindService這種引用所特有的、在回收內(nèi)存之前必須做的準備工作。

當只有startService這種引用時,調(diào)用stopService后,不需要準備工作,Service直接被回收;當只有bindService這種引用時,調(diào)用unbindService,回收工作分兩步走:第一,準備工作。第二,才是回收內(nèi)存。

當一個Service對象同時擁有這兩種引用時的邏輯也就容易理解了吧。

Service運行在什么線程

startService --> stopService --> bindService -->unbindService

//startService方式
E/Service: Service Thread --> main
E/Service: ----- onCreate -----
E/Service: ----- onStartCommand -----
E/Service: ----- onDestroy -----
//bindService方式
E/Service: Service Thread --> main
E/Service: ----- onCreate -----
E/Service: ----- onBind -----
E/Service: ----- onServiceConnected -----
E/Service: -----Binder  doSth -----
E/Service: Binder Thread --> main
E/Service: ----- onUnbind -----
E/Service: ----- onDestroy -----

默認情況下,service代碼是運行在UI線程的,所以耗時操作需要開啟子線程。
這里介紹一個封裝好的Service類。

/**
 * 調(diào)用方式與傳統(tǒng)Service相同
 * 每一個耗時操作會以工作隊列的方式在IntentService的onHandleIntent回調(diào)方法中執(zhí)行
 * 不會阻塞UI線程
 * 任務(wù)執(zhí)行完畢,自動結(jié)束
 * 默認實現(xiàn)的onStartCommand()的目的是將intent插入到工作隊列中
 */
public class MyIntentService extends IntentService {

    final String TAG = "Service";

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        LogTool.e(TAG, "MyIntentService onCreate Thread --> " + Thread.currentThread().getName());
        LogTool.e(TAG, "----- onCreate -----");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogTool.e(TAG, "----- onDestroy -----");
    }

    //    處理一下耗時任務(wù)
    @Override
    protected void onHandleIntent(Intent intent) {

        LogTool.e(TAG, "MyIntentService onHandleIntent Thread --> " + Thread.currentThread().getName());
        LogTool.e(TAG, "----- onHandleIntent -----");

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

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        LogTool.e(TAG, "----- onStart -----");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogTool.e(TAG, "----- onStartCommand -----");
        return super.onStartCommand(intent, flags, startId);
    }
}

startService

E/Service: MyIntentService onCreate Thread --> main
E/Service: ----- onCreate -----
E/Service: ----- onStartCommand -----
E/Service: ----- onStart -----
E/Service: MyIntentService onHandleIntent Thread --> IntentService[MyIntentService]
E/Service: ----- onHandleIntent -----
//6秒鐘之后onDestroy,因為sleep了6000毫秒
E/Service: ----- onDestroy -----

so,onHandleIntent 是可以執(zhí)行耗時操作的。

對Service的理解

  1. 如何理解activity在前臺,service在后臺?
    個人認為,這里的“前”和“后”指的是,是否有一個可視的界面作為依托。
  2. service默認運行在主線程,那它又有什么卵用呢?
    如果要做一個音樂播放器,難道把播放音樂的邏輯放在某個activity里么?activity被銷毀了,音樂就停了?這時候就非常需要一個不依靠界面而存在東西,而且,所有的Activity都可以與Service進行關(guān)聯(lián),然后可以很方便地操作其中的方法,即使Activity被銷毀了,之后只要重新與Service建立關(guān)聯(lián),就又能夠獲取到原有的Service中Binder的實例。那感覺就像“你看得見,或看不見它,它就在那里”。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容