編輯:關於 Android 程式設計
Service 是 Android 四大組件之一,在實際開發中扮演著舉足輕重的角色。先看官方對它的定義:
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC).
簡單來說,Service 是一個沒有使用者介面、在背景執行耗時工作的應用組件。其他組件可以將它啟動,即便使用者切換到別的應用,它依然會在背景持續運行;組件也能透過綁定(bind)與它互動,甚至進行跨進程通信(IPC)。諸如網路傳輸、音樂播放、檔案讀寫、與 ContentProvider 交互等工作,都可以交給它在背景完成。
Service 有兩種基本狀態:「已啟動(Started)」與「已綁定(Bound)」。
當某個應用組件(例如 Activity)呼叫 startService() 啟動服務時,它就進入「已啟動」狀態。一旦啟動,Service 便會在背景無限期運行,哪怕啟動它的組件已經被銷毀。這類服務通常只執行單一操作,且不會把結果回傳給呼叫者,例如下載或上傳檔案;任務結束後,服務應該自行停止。
當組件透過 bindService() 綁定服務時,它便進入「已綁定」狀態。此時服務提供了一個客戶端—伺服器介面,讓組件能夠發送請求、取得結果,甚至跨進程(IPC)互動。綁定狀態的服務只在至少有一個組件與它保持綁定時才會運行;多個組件可以同時綁定同一個服務,但當所有組件都解除綁定後,服務便會被銷毀。
官方文件還特別提醒:
Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations, you should create a new thread within the service to do that work.
換句話說,Service 和 Activity 一樣運行在當前進程的主線程中。因此,凡是會阻塞 UI 的耗時操作都不能直接寫在 Service 裡,而應另開一條執行緒來處理,例如網路請求。若在 Service 中進行高 CPU 佔用或長時間的運算,就可能觸發 ANR(Application Not Responding)而彈出「強制關閉還是等待」的對話框。可以這樣理解:Service 就是一個與 Activity 平級、只是看不見、在背景默默運作的組件,這也是它與 Activity 並列為 Android 基本組件的原因。
Service 生命週期中的一些關鍵方法:

下面是一個示範 Service 各回調方法的範例:
public class MyService extends Service {
private int localCount = 0;
class MyIBinder extends Binder implements LocalService {
@Override
public int getCount() {
return localCount;
}
}
@Override
public void onCreate() {
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Log.i("MyService", "onCreate:" + localCount);
Thread.sleep(1000);
localCount++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.i("MyService", "onStart");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("MyService", "onDestroy");
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("MyService", "onUnbind");
return super.onUnbind(intent);
}
@Override
public IBinder onBind(Intent arg0) {
Log.i("MyService", "onBind");
return new MyIBinder();
}
}
關於 Service 生命週期,網路上還有一張更為直觀的流程圖:

1. Service 是 Android 的一種機制。當它運行時,如果是 Local Service,對應的 Service 運行在主進程的 main 執行緒上;如果是 Remote Service,則運行在獨立進程的 main 執行緒上。無論是遠端還是本地 Service,它與呼叫者之間的通訊都是同步的,這與執行緒並無直接關係。
2. Thread 的運行獨立於 Activity。也就是說,當一個 Activity 被 finish 之後,若你沒有主動停止執行緒,或 run 方法尚未執行完畢,執行緒仍會繼續運行。這會帶來一個問題:Activity 被 finish 後,你不再持有該執行緒的引用,下次啟動時便無法控制先前建立的執行緒,而 Service 則可以。此外,你也無法在不同的 Activity 之間對同一條執行緒進行統一控制。
3. 你也可以在 Service 中註冊 BroadcastReceiver,在其他地方透過發送廣播來控制它,這些都是單純的 Thread 無法做到的。
這裡要介紹 Service 的一個子類——IntentService。先看官方說明:
This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.
IntentService 以佇列的方式把請求的 Intent 逐一加入,然後開啟一條 worker thread 來處理佇列中的 Intent。對於非同步的 startService 請求,它會處理完一個再處理下一個,每個請求都在獨立的 worker thread 中執行,不會阻塞應用主線程。這提供了一個思路:若有耗時操作,與其自己在 Service 裡另開執行緒,不如直接使用 IntentService。一般的 Service 若要做耗時任務必須自行開啟執行緒,而 IntentService 預設就實作了一條 worker thread,可以直接在其中進行耗時運算。
IntentService 的具體實作如下:
public class HelloIntentService extends IntentService {
public HelloIntentService() {
super("HelloIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
// 通常會在這裡做一些工作,如下載檔案。
// 此範例只是暫停 5 秒。
long endTime = System.currentTimeMillis() + 5 * 1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
如果 Service 是非綁定型的,任務完成後為了節省系統資源,一定要停止它。可以透過 stopSelf() 自行停止,也可以由其他組件呼叫 stopService() 停止;綁定型的 Service 則可透過 onUnBind() 來結束。
若你在 Service 中啟動了新的執行緒,服務結束時務必留意是否需要終止該執行緒,否則不僅浪費資源,還可能導致業務邏輯出錯。例如下面這段程式,即使 Service 已結束,new Thread 仍會繼續運行:
public void onCreate() {
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Log.i("MyService", "onCreate:" + localCount);
Thread.sleep(1000);
localCount++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
super.onCreate();
}

Service 與 Activity 的通訊手段很多,如 IBinder、Broadcast 等,本文介紹另一種方式:Messenger。
官方文件說明:Messenger 引用了一個 Handler 對象,讓其他對象能夠向它發送訊息(透過 mMessenger.send(Message msg))。它允許跨進程基於 Message 的通訊——也就是說,兩個進程之間可以透過 Message 交流。服務端用 Handler 建立一個 Messenger,客戶端只要持有這個 Messenger,就能與服務端通訊。
過去我們用 Handler + Message 通訊,都是在同一進程內,由執行緒持有主線程的 Handler 並向主線程發送訊息。既然 Android 的 Binder 機制支援跨進程通訊,我們自然可以把 Handler 與 Binder 結合起來實現跨進程發送訊息。查看 API 就會發現,Messenger 正是這種方式的實作。
一般使用步驟如下:
1. 遠端透過 mMessenger = new Messenger(mHandler) 建立一個信使對象;
2. 客戶端使用 bindService 請求連接遠端;
3. 遠端在 onBind 方法中返回一個 Binder:return mMessenger.getBinder();
4. 客戶端使用遠端返回的 Binder 得到一個信使(即遠端信使);
public void onServiceConnected(ComponentName name, IBinder service) {
rMessenger = new Messenger(service);
...
}
這裡雖然 new 了一個 Messenger,但看它的實作:
public Messenger(IBinder target) { mTarget = IMessenger.Stub.asInterface(target); }
可以發現 mTarget 是透過 AIDL 得到的,實際上就是遠端建立的那個。
5. 客戶端使用這個遠端信使向遠端發送訊息:rMessenger.send(msg);,此時遠端服務的 Handler 便能收到訊息,並在其 handleMessage(Message msg) 方法中處理(該 Handler 就是第一步中建立 Messenger 時傳入的 mHandler)。
經過這五個步驟,訊息傳遞看似只是客戶端向服務端的單向發送。那麼如何實現雙向傳遞呢?
首先在第五步稍作修改,在 send(msg) 前透過 msg.replyTo = mMessenger 把自己的信使設定到訊息中,這樣服務端收到訊息時也一併拿到了客戶端的信使對象,接著服務端便能向客戶端發送訊息:
cMessenger = msg.replyTo; cMessenger.send(message);
如此一來,客戶端就能在自己的 Handler 的 handleMessage 方法中接收並處理服務端送來的訊息,雙向通訊宣告完成。
客戶端範例:
public class Binding extends Activity implements View.OnClickListener {
private Messenger mMessenger;
private Messenger rMessenger;
private TextView mCallbackText;
private boolean isBound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MessengerService.MSG_SET_VALUE:
mCallbackText.setText("Received from service: " + msg.arg1);
break;
default:
break;
}
}
};
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
rMessenger = new Messenger(service);
mMessenger = new Messenger(mHandler);
sendInitMessage();
}
public void onServiceDisconnected(ComponentName name) {
rMessenger = null;
}
};
private void sendInitMessage() {
Message message = Message.obtain(null, MessengerService.MSG_SET_VALUE);
message.replyTo = mMessenger;
try {
rMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void onClick(View v) {
Intent intent = new Intent("com.app.messenger_service");
switch (v.getId()) {
case R.id.bind:
if (!isBound) {
isBound = bindService(intent, connection, BIND_AUTO_CREATE);
}
break;
case R.id.unbind:
if (isBound) {
unbindService(connection);
isBound = false;
}
break;
default:
break;
}
}
private void initView() {
findViewById(R.id.bind).setOnClickListener(this);
findViewById(R.id.unbind).setOnClickListener(this);
mCallbackText = (TextView) findViewById(R.id.callback);
mCallbackText.setText("Not attached.");
}
}
服務端範例:
public class MessengerService extends Service {
private Messenger cMessenger;
private boolean connecting = false;
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_VALUE = 3;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SET_VALUE:
try {
Message message = Message.obtain(null, MessengerService.MSG_SET_VALUE);
message.arg1 = 0;
cMessenger = msg.replyTo;
cMessenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
};
private Messenger mMessenger = new Messenger(mHandler);
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
connecting = false;
return super.onUnbind(intent);
}
@Override
public IBinder onBind(Intent intent) {
connecting = true;
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
try {
while (connecting) {
Message message = Message.obtain(null, MSG_SET_VALUE);
Thread.sleep(1000);
message.arg1 = i++;
cMessenger.send(message);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}).start();
return mMessenger.getBinder();
}
@Override
public void onRebind(Intent intent) {
Toast.makeText(this, "onRebind", Toast.LENGTH_SHORT).show();
}
}
手把手教你制作 Android 音樂播放器(Service + 廣播)
先欣賞一下這個清爽的播放器界面吧~ 如果只用 Activity 來實現這樣的功能就太過小兒科了,這裡我們採用 Service。幾個關鍵點先說明: 1、若要在 Activ
Android SparseArray詳解:為何用它取代HashMap
近來寫程式時,Android Studio對某段以HashMap<Integer, E>為主的程式碼給出了效能提示: 翻譯過來的意思是:改用SparseAr
一文吃透 Android 各種通信機制:組件、進程、線程與跨應用
什麼是通信? 通信,顧名思義,就是資訊的傳遞與交換。在 Android 這套龐大的體系裡,通信貫穿始終,是每一名開發者都必須跨過的門檻。 讀完本文,你將收穫什麼 依照目
從 MVP 到 MVVM:Android DataBinding 帶來的架構升級
1、DataBinding:再見 MVP,你好 MVVM 談到 Android 應用程式的架構模式,MVP 長期佔據主流地位。Ted Mosby、Nucleus、Mort