一、Service的種類 html
按運行地點分類: java
類別 | 區別 | 優勢 | 缺點 | 應用 |
本地服務(Local) | 該服務依附在主進程上, | 服務依附在主進程上而不是獨立的進程,這樣在必定程度上節約了資源,另外Local服務由於是在同一進程所以不須要IPC,也不須要AIDL。相應bindService會方便不少。 | 主進程被Kill後,服務便會終止。 | 很是常見的應用如:HTC的音樂播放服務,每天動聽音樂播放服務。 |
遠程服務(Remote) | 該服務是獨立的進程, | 服務爲獨立的進程,對應進程名格式爲所在包名加上你指定的android:process字符串。因爲是獨立的進程,所以在Activity所在進程被Kill的時候,該服務依然在運行,不受其餘進程影響,有利於爲多個進程提供服務具備較高的靈活性。 | 該服務是獨立的進程,會佔用必定資源,而且使用AIDL進行IPC稍微麻煩一點。 | 一些提供系統服務的Service,這種Service是常駐的。 |
其實remote服務仍是不多見的,而且通常都是系統服務。 android
按運行類型分類: 服務器
類別 | 區別 | 應用 |
前臺服務 | 會在通知一欄顯示 ONGOING 的 Notification, | 當服務被終止的時候,通知一欄的 Notification 也會消失,這樣對於用戶有必定的通知做用。常見的如音樂播放服務。 |
後臺服務 | 默認的服務即爲後臺服務,即不會在通知一欄顯示 ONGOING 的 Notification。 | 當服務被終止的時候,用戶是看不到效果的。某些不須要運行或終止提示的服務,如天氣更新,日期同步,郵件同步等。 |
有同窗可能會問,後臺服務咱們能夠本身建立 ONGOING 的 Notification 這樣就成爲前臺服務嗎?答案是否認的,前臺服務是在作了上述工做以後須要調用 startForeground ( android 2.0 及其之後版本 )或 setForeground (android 2.0 之前的版本)使服務成爲 前臺服務。這樣作的好處在於,當服務被外部強制終止掉的時候,ONGOING 的 Notification 任然會移除掉。 架構
按使用方式分類: app
類別 | 區別 |
startService 啓動的服務 | 主要用於啓動一個服務執行後臺任務,不進行通訊。中止服務使用stopService |
bindService 啓動的服務 | 該方法啓動的服務要進行通訊。中止服務使用unbindService |
startService 同時也 bindService 啓動的服務 | 中止服務應同時使用stepService與unbindService |
以上面三種方式啓動的服務其生命週期也有區別,將在隨後給出。 框架
二、Service 與 Thread 的區別 異步
不少時候,你可能會問,爲何要用 Service,而不用 Thread 呢,由於用 Thread 是很方便的,比起 Service 也方便多了,下面我詳細的來解釋一下。 ide
1). Thread:Thread 是程序執行的最小單元,它是分配CPU的基本單位。能夠用 Thread 來執行一些異步的操做。 函數
2). Service:Service 是android的一種機制,當它運行的時候若是是Local Service,那麼對應的 Service 是運行在主進程的 main 線程上的。如:onCreate,onStart 這些函數在被系統調用的時候都是在主進程的 main 線程上運行的。若是是Remote Service,那麼對應的 Service 則是運行在獨立進程的 main 線程上。所以請不要把 Service 理解成線程,它跟線程半毛錢的關係都沒有!
既然這樣,那麼咱們爲何要用 Service 呢?其實這跟 android 的系統機制有關,咱們先拿 Thread 來講。Thread 的運行是獨立於 Activity 的,也就是說當一個 Activity 被 finish 以後,若是你沒有主動中止 Thread 或者 Thread 裏的 run 方法沒有執行完畢的話,Thread 也會一直執行。所以這裏會出現一個問題:當 Activity 被 finish 以後,你再也不持有該 Thread 的引用。另外一方面,你沒有辦法在不一樣的 Activity 中對同一 Thread 進行控制。
舉個例子:若是你的 Thread 須要不停地隔一段時間就要鏈接服務器作某種同步的話,該 Thread 須要在 Activity 沒有start的時候也在運行。這個時候當你 start 一個 Activity 就沒有辦法在該 Activity 裏面控制以前建立的 Thread。所以你便須要建立並啓動一個 Service ,在 Service 裏面建立、運行並控制該 Thread,這樣便解決了該問題(由於任何 Activity 均可以控制同一 Service,而系統也只會建立一個對應 Service 的實例)。
所以你能夠把 Service 想象成一種消息服務,而你能夠在任何有 Context 的地方調用 Context.startService、Context.stopService、Context.bindService,Context.unbindService,來控制它,你也能夠在 Service 裏註冊 BroadcastReceiver,在其餘地方經過發送 broadcast 來控制它,固然這些都是 Thread 作不到的。
三、Service的生命週期
onCreate onStart onDestroy onBind
1). 被啓動的服務的生命週期:若是一個Service被某個Activity 調用 Context.startService 方法啓動,那麼無論是否有Activity使用bindService綁定或unbindService解除綁定到該Service,該Service都在後臺運行。若是一個Service被startService 方法屢次啓動,那麼onCreate方法只會調用一次,onStart將會被調用屢次(對應調用startService的次數),而且系統只會建立Service的一個實例(所以你應該知道只須要一次stopService調用)。該Service將會一直在後臺運行,而無論對應程序的Activity是否在運行,直到被調用stopService,或自身的stopSelf方法。固然若是系統資源不足,android系統也可能結束服務。
2). 被綁定的服務的生命週期:若是一個Service被某個Activity 調用 Context.bindService 方法綁定啓動,無論調用 bindService 調用幾回,onCreate方法都只會調用一次,同時onStart方法始終不會被調用。當鏈接創建以後,Service將會一直運行,除非調用Context.unbindService 斷開鏈接或者以前調用bindService 的 Context 不存在了(如Activity被finish的時候),系統將會自動中止Service,對應onDestroy將被調用。
3). 被啓動又被綁定的服務的生命週期:若是一個Service又被啓動又被綁定,則該Service將會一直在後臺運行。而且無論如何調用,onCreate始終只會調用一次,對應startService調用多少次,Service的onStart便會調用多少次。調用unbindService將不會中止Service,而必須調用 stopService 或 Service的 stopSelf 來中止服務。
4). 當服務被中止時清除服務:當一個Service被終止(一、調用stopService;二、調用stopSelf;三、再也不有綁定的鏈接(沒有被啓動))時,onDestroy方法將會被調用,在這裏你應當作一些清除工做,如中止在Service中建立並運行的線程。
特別注意:
一、你應當知道在調用 bindService 綁定到Service的時候,你就應當保證在某處調用 unbindService 解除綁定(儘管 Activity 被 finish 的時候綁定會自 動解除,而且Service會自動中止);
二、你應當注意 使用 startService 啓動服務以後,必定要使用 stopService中止服務,無論你是否使用bindService;
三、同時使用 startService 與 bindService 要注意到,Service 的終止,須要unbindService與stopService同時調用,才能終止 Service,無論 startService 與 bindService 的調用順序,若是先調用 unbindService 此時服務不會自動終止,再調用 stopService 以後服務纔會中止,若是先調用 stopService 此時服務也不會終止,而再調用 unbindService 或者 以前調用 bindService 的 Context 不存在了(如Activity 被 finish 的時候)以後服務纔會自動中止;
四、當在旋轉手機屏幕的時候,當手機屏幕在「橫」「豎」變換時,此時若是你的 Activity 若是會自動旋轉的話,旋轉實際上是 Activity 的從新建立,所以旋轉以前的使用 bindService 創建的鏈接便會斷開(Context 不存在了),對應服務的生命週期與上述相同。
五、在 sdk 2.0 及其之後的版本中,對應的 onStart 已經被否決變爲了 onStartCommand,不過以前的 onStart 任然有效。這意味着,若是你開發的應用程序用的 sdk 爲 2.0 及其之後的版本,那麼你應當使用 onStartCommand 而不是 onStart。
四、startService 啓動服務
想要用 startService 啓動服務,無論Local 仍是 Remote 咱們須要作的工做都是同樣簡單。固然要記得在 Androidmanifest.xml 中註冊 service。
根據上面的生命週期,咱們便會給出 Service 中的代碼框架:
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
|
packagecom.newcj.test;
importandroid.app.Service;
importandroid.content.Intent;
importandroid.os.IBinder;
publicclassLocalService1extendsService {
/**
* onBind 是 Service 的虛方法,所以咱們不得不實現它。
* 返回 null,表示客服端不能創建到此服務的鏈接。
*/
@Override
publicIBinder onBind(Intent intent) {
returnnull;
}
@Override
publicvoidonCreate() {
super.onCreate();
}
@Override
publicvoidonStart(Intent intent,intstartId) {
super.onStart(intent, startId);
}
@Override
publicvoidonDestroy() {
super.onDestroy();
}
}
|
對應生命週期系統回調函數上面已經說明,在對應地方加上適當的代碼便可。下面是啓動與中止 Service 的代碼:
1
2
3
4
5
|
// 啓動一個 Activity
startActivity(newIntent(this, LocalService1.class));
...
// 中止一個 Activity
stopService(newIntent(this, LocalService1.class));
|
對應的 Intent 爲標誌服務類的 Intent。
五、Local 與 Remote 服務綁定
一樣記得在 Androidmanifest.xml 中註冊 service
1). Local 服務綁定:Local 服務的綁定較簡單,首先在 Service 中咱們須要實現 Service 的抽象方法 onBind,並返回一個實現 IBinder 接口的對象。
Service 中的代碼:
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
|
packagecom.newcj.test;
importandroid.app.Service;
importandroid.content.Intent;
importandroid.os.Binder;
importandroid.os.IBinder;
publicclassLocalServiceextendsService {
/**
* 在 Local Service 中咱們直接繼承 Binder 而不是 IBinder,由於 Binder 實現了 IBinder 接口,這樣咱們能夠少作不少工做。
* @author newcj
*/
publicclassSimpleBinderextendsBinder{
/**
* 獲取 Service 實例
* @return
*/
publicLocalService getService(){
returnLocalService.this;
}
publicintadd(inta,intb){
returna + b;
}
}
publicSimpleBinder sBinder;
@Override
publicvoidonCreate() {
super.onCreate();
// 建立 SimpleBinder
sBinder =newSimpleBinder();
}
@Override
publicIBinder onBind(Intent intent) {
// 返回 SimpleBinder 對象
returnsBinder;
}
}
|
上面的代碼關鍵之處,在於 onBind(Intent) 這個方法 返回了一個實現了 IBinder 接口的對象,這個對象將用於綁定Service 的 Activity 與 Local Service 通訊。下面是 Activity 中的代碼:
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
47
48
49
50
51
52
53
54
55
56
|
packagecom.newcj.test;
importandroid.app.Activity;
importandroid.content.ComponentName;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.ServiceConnection;
importandroid.os.Bundle;
importandroid.os.IBinder;
importandroid.util.Log;
importandroid.view.View;
importandroid.view.View.OnClickListener;
publicclassMainextendsActivity {
privatefinalstaticString TAG ="SERVICE_TEST";
privateServiceConnection sc;
privatebooleanisBind;
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sc =newServiceConnection() {
@Override
publicvoidonServiceDisconnected(ComponentName name) {
}
@Override
publicvoidonServiceConnected(ComponentName name, IBinder service) {
LocalService.SimpleBinder sBinder = (LocalService.SimpleBinder)service;
Log.v(TAG,"3 + 5 = "+ sBinder.add(3,5));
Log.v(TAG, sBinder.getService().toString());
}
};
findViewById(R.id.btnBind).setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View v) {
bindService(newIntent(Main.this, LocalService.class), sc, Context.BIND_AUTO_CREATE);
isBind =true;
}
});
findViewById(R.id.btnUnbind).setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View v) {
if(isBind){
unbindService(sc);
isBind =false;
}
}
});
}
}
|
在 Activity 中,咱們經過 ServiceConnection 接口來取得創建鏈接 與 鏈接意外丟失的回調。bindService有三個參數,第一個是用於區分 Service 的Intent 與 startService 中的 Intent 一致,第二個是實現了 ServiceConnection 接口的對象,最後一個是 flag 標誌位。有兩個flag,BIND_DEBUG_UNBIND 與 BIND_AUTO_CREATE,前者用於調試(詳細內容能夠查看javadoc 上面描述的很清楚),後者默認使用。unbindService 解除綁定,參數則爲以前建立的 ServiceConnection 接口對象。另外,屢次調用 unbindService 來釋放相同的鏈接會拋出異常,所以我建立了一個 boolean 變量來判斷是否 unbindService 已經被調用過。
運行結果:
2). Remote 服務綁定:Remote 的服務綁定因爲服務是在另一個進程,所以須要用到 android 的 IPC 機制。這將又是一個很長的話題,所以,我打算寫另一篇 android 的 IPC 機制分析 ,並在其中進行詳述,而後在這裏更新連接,敬請關注。
特別注意:
一、Service.onBind若是返回null,則調用 bindService 會啓動 Service,但不會鏈接上 Service,所以 ServiceConnection.onServiceConnected 不會被調用,但你任然須要使用 unbindService 函數斷開它,這樣 Service 纔會中止。
六、建立前臺服務
前臺服務的優勢上面已經說明,但設置服務爲前臺服務,咱們須要注意在 sdk 2.0 及其之後版本使用的方法是 startForeground 與 stopForeground,以前版本使用的是 setForeground ,所以若是你應用程序的最低運行環境要求是 2.0,那麼這裏能夠直接運用新方法,若是運行環境是2.0如下,那麼爲了保證向後兼容性,這裏必須使用反射技術來調用新方法。
下面是我仿照 ApiDemos 從新敲的代碼,對某些地方進行了修改,所以更具備說明性:
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
packagecom.newcj.test;
importjava.lang.reflect.InvocationTargetException;
importjava.lang.reflect.Method;
importandroid.app.Notification;
importandroid.app.NotificationManager;
importandroid.app.PendingIntent;
importandroid.app.Service;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.os.IBinder;
publicclassForegroundServiceextendsService {
privatestaticfinalClass[] mStartForegroundSignature =newClass[] {
int.class, Notification.class};
privatestaticfinalClass[] mStopForegroundSignature =newClass[] {
boolean.class};
privateNotificationManager mNM;
privateMethod mStartForeground;
privateMethod mStopForeground;
privateObject[] mStartForegroundArgs =newObject[2];
privateObject[] mStopForegroundArgs =newObject[1];
@Override
publicIBinder onBind(Intent intent) {
returnnull;
}
@Override
publicvoidonCreate() {
super.onCreate();
mNM = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
try{
mStartForeground = ForegroundService.class.getMethod("startForeground", mStartForegroundSignature);
mStopForeground = ForegroundService.class.getMethod("stopForeground", mStopForegroundSignature);
}catch(NoSuchMethodException e) {
mStartForeground = mStopForeground =null;
}
// 咱們並不須要爲 notification.flags 設置 FLAG_ONGOING_EVENT,由於
// 前臺服務的 notification.flags 老是默認包含了那個標誌位
Notification notification =newNotification(R.drawable.icon,"Foreground Service Started.",
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this,0,
newIntent(this, Main.class),0);
notification.setLatestEventInfo(this,"Foreground Service",
"Foreground Service Started.", contentIntent);
// 注意使用 startForeground ,id 爲 0 將不會顯示 notification
startForegroundCompat(1, notification);
}
@Override
publicvoidonDestroy() {
super.onDestroy();
stopForegroundCompat(1);
}
// 以兼容性方式開始前臺服務
privatevoidstartForegroundCompat(intid, Notification n){
if(mStartForeground !=null){
mStartForegroundArgs[0] = id;
mStartForegroundArgs[1] = n;
try{
mStartForeground.invoke(this, mStartForegroundArgs);
}catch(IllegalArgumentException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}catch(InvocationTargetException e) {
e.printStackTrace();
}
return;
}
setForeground(true);
mNM.notify(id, n);
}
// 以兼容性方式中止前臺服務
privatevoidstopForegroundCompat(intid){
if(mStopForeground !=null){
mStopForegroundArgs[0] = Boolean.TRUE;
try{
mStopForeground.invoke(this, mStopForegroundArgs);
}catch(IllegalArgumentException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}catch(InvocationTargetException e) {
e.printStackTrace();
}
return;
}
// 在 setForeground 以前調用 cancel,由於咱們有可能在取消前臺服務以後
// 的那一瞬間被kill掉。這個時候 notification 便永遠不會從通知一欄移除
mNM.cancel(id);
setForeground(false);
}
}
|
特別注意:
一、使用 startForeground ,若是 id 爲 0 ,那麼 notification 將不會顯示。
七、在什麼狀況下使用 startService 或 bindService 或 同時使用startService 和 bindService
若是你只是想要啓動一個後臺服務長期進行某項任務那麼使用 startService 即可以了。若是你想要與正在運行的 Service 取得聯繫,那麼有兩種方法,一種是使用 broadcast ,另外是使用 bindService ,前者的缺點是若是交流較爲頻繁,容易形成性能上的問題,而且 BroadcastReceiver 自己執行代碼的時間是很短的(也許執行到一半,後面的代碼便不會執行),然後者則沒有這些問題,所以咱們確定選擇使用 bindService(這個時候你便同時在使用 startService 和 bindService 了,這在 Activity 中更新 Service 的某些運行狀態是至關有用的)。另外若是你的服務只是公開一個遠程接口,供鏈接上的客服端(android 的 Service 是C/S架構)遠程調用執行方法。這個時候你能夠不讓服務一開始就運行,而只用 bindService ,這樣在第一次 bindService 的時候纔會建立服務的實例運行它,這會節約不少系統資源,特別是若是你的服務是Remote Service,那麼該效果會越明顯(固然在 Service 建立的時候會花去必定時間,你應當注意到這點)。
八、在 AndroidManifest.xml 裏 Service 元素的常見選項
android:name ------------- 服務類名
android:label -------------- 服務的名字,若是此項不設置,那麼默認顯示的服務名則爲類名
android:icon -------------- 服務的圖標
android:permission ------- 申明此服務的權限,這意味着只有提供了該權限的應用才能控制或鏈接此服務
android:process ---------- 表示該服務是否運行在另一個進程,若是設置了此項,那麼將會在包名後面加上這段字符串表示另外一進程的名字
android:enabled ---------- 若是此項設置爲 true,那麼 Service 將會默認被系統啓動,不設置默認此項爲 false
android:exported --------- 表示該服務是否可以被其餘應用程序所控制或鏈接,不設置默認此項爲 false