Android Service的生命週期

Service作爲Android四大組件之一,應用非常廣泛。 
 和activity一樣,service也有一系列的生命週期回調函數,你可以實現它們來監測service狀態的變化,並且在適當的時候執行適當的工作。

服務一般分爲兩種:

1:本地服務, Local Service 用於應用程序內部。在Service可以調用Context.startService()啓動,調用Context.stopService()結束。 在內部可以調用Service.stopSelf() 或 Service.stopSelfResult()來自己停止。無論調用了多少次startService(),都只需調用一次 stopService()來停止。

2:遠程服務, Remote Service 用於android系統內部的應用程序之間。可以定義接口並把接口暴露出來,以便其他應用進行操作。客戶端建立到服務對象的連接,並通過那個連接來調用服 務。調用Context.bindService()方法建立連接,並啓動,以調用 Context.unbindService()關閉連接。多個客戶端可以綁定至同一個服務。如果服務此時還沒有加載,bindService()會先加 載它。 
提供給可被其他應用複用,比如定義一個天氣預報服務,提供與其他應用調用即可。

Android Service的生命週期
說到service生命週期,我們來建個類繼承一下service看看

週期圖:

public class DemoService extends Service {


    @Override
    public void onCreate() {
        super.onCreate();
        // The service is being created
        創建服務
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
        // The service is starting, due to a call to startService()
        開始服務
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
        綁定服務
        // A client is binding to the service with bindService()
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
        // All clients have unbound with unbindService()
        解綁服務
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        // A client is binding to the service with bindService(),
        // after onUnbind() has already been called
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        銷燬服務
        // The service is no longer used and is being destroyed
    }
 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
如何啓動服務,外部方法有哪些?
startService(),啓動服務 
stopService(),停止服務 
bindService(),綁定服務 
unbindService(),解綁服務

生命週期方法簡單介紹
startService()
作用:啓動Service服務 
手動調用startService()後,自動調用內部方法:onCreate()、onStartCommand() 
如果一個service被startService多次啓動,onCreate()只會調用一次 
onStartCommand()調用次數=startService()次數

stopService()
作用:關閉Service服務 
手動調用stopService()後,自動調用內部方法:onDestory() 
如果一個service被啓動且被綁定,如果沒有在綁定的前提下stopService()是無法停止服務的。

bindService()
作用:綁定Service服務 
手動調用bindService()後,自動調用內部方法:onCreate()、onBind()

unbindService()
作用:解綁Service服務 
手動調用unbindService()後,自動調用內部方法:onCreate()、onBind()、onDestory()

注意
startService()和stopService()只能開啓和關閉Service,無法操作Service; 
bindService()和unbindService()可以操作Service

startService開啓的Service,調用者退出後Service仍然存在; 
BindService開啓的Service,調用者退出後,Service隨着調用者銷燬。

以上是對服務的簡單講述,接下來會講解更多。
--------------------- 
作者:碼蛋蛋 
來源:CSDN 
原文:https://blog.csdn.net/u013933720/article/details/78260446 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章