編輯:關於 Android 程式設計
Android 中使用 Service 主要有兩條路:呼叫 Context.startService(),或呼叫 Context.bindService()。本文只討論純 bindService 的情境,完全不涉及 startService;關於後者,可參考〈Android 中 startService 的使用及 Service 生命週期〉。
1. bindService 啟動的 Service 在呼叫者與服務之間形成典型的 client-server 介面:呼叫者是客戶端,Service 是服務端。Service 只有一個,但綁定到它上面的 client 可以是一個或多個。這裡所說的 client 指的是「元件」,例如某個 Activity——同一個 Activity 內多次呼叫 bindService,對 Service 而言仍然只是一個 client。
2. client 可以透過 IBinder 介面取得 Service 的實例,於是在 client 端就能直接呼叫 Service 的方法,互動方式相當靈活;配合 IBinder 還能實現跨進程的 client-server 溝通,這是純 startService 做不到的。
3. 不同於 startService 啟動的服務預設無限期執行(需靠 stopService() 或 stopSelf() 主動停止),bindService 啟動的服務生命週期與綁定的 client 緊密相關。當 client 銷毀時會自動解除綁定,當然也可以明確呼叫 unbindService()。當再無任何 client 綁定時,Service 便自行銷毀。
4. 兩者觸發的回呼不同:startService 走 onStartCommand(),bindService 走 onBind()、onUnbind() 等。
使用 bindService 大致分兩種情形:一是 client 與 Service 在同一個 App 內;二是 client 在 App1、Service 在 App2,屬於跨進程溝通。本文聚焦第一種,因為它也是實務上最常見的。
先定義 TestService,它是 client-server 結構中的 server 端,並在每個生命週期回呼裡加上日誌:
package com.ispring.startservicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.Random;
public class TestService extends Service {
public class MyBinder extends Binder {
public TestService getService() {
return TestService.this;
}
}
// 透過 binder 實現 client 與 Service 之間的溝通
private MyBinder binder = new MyBinder();
private final Random generator = new Random();
@Override
public void onCreate() {
Log.i("DemoLog", "TestService -> onCreate, Thread: " + Thread.currentThread().getName());
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("DemoLog", "TestService -> onStartCommand, startId: " + startId
+ ", Thread: " + Thread.currentThread().getName());
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
Log.i("DemoLog", "TestService -> onBind, Thread: " + Thread.currentThread().getName());
return binder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("DemoLog", "TestService -> onUnbind, from: " + intent.getStringExtra("from"));
return false;
}
@Override
public void onDestroy() {
Log.i("DemoLog", "TestService -> onDestroy, Thread: " + Thread.currentThread().getName());
super.onDestroy();
}
/** Service 對外公開、供 client 呼叫的方法 */
public int getRandomNumber() {
return generator.nextInt();
}
}
App 中另有兩個 Activity:ActivityA(啟動畫面)與 ActivityB,兩者都是 client。

ActivityA 的程式碼:
public class ActivityA extends Activity implements Button.OnClickListener {
private TestService service = null;
private boolean isBound = false;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
isBound = true;
TestService.MyBinder myBinder = (TestService.MyBinder) binder;
service = myBinder.getService();
Log.i("DemoLog", "ActivityA onServiceConnected");
int num = service.getRandomNumber();
Log.i("DemoLog", "ActivityA 中調用 TestService 的 getRandomNumber 方法, 結果: " + num);
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
Log.i("DemoLog", "ActivityA onServiceDisconnected");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
Log.i("DemoLog", "ActivityA -> onCreate, Thread: " + Thread.currentThread().getName());
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnBindService) {
Intent intent = new Intent(this, TestService.class);
intent.putExtra("from", "ActivityA");
Log.i("DemoLog", "ActivityA 執行 bindService");
bindService(intent, conn, BIND_AUTO_CREATE);
} else if (v.getId() == R.id.btnUnbindService) {
if (isBound) {
Log.i("DemoLog", "ActivityA 執行 unbindService");
unbindService(conn);
}
} else if (v.getId() == R.id.btnStartActivityB) {
Log.i("DemoLog", "ActivityA 啟動 ActivityB");
startActivity(new Intent(this, ActivityB.class));
} else if (v.getId() == R.id.btnFinish) {
Log.i("DemoLog", "ActivityA 執行 finish");
this.finish();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("DemoLog", "ActivityA -> onDestroy");
}
}
ActivityB 的結構幾乎相同,只是少了啟動其他 Activity 的按鈕:

public class ActivityB extends Activity implements Button.OnClickListener {
private TestService service = null;
private boolean isBound = false;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
isBound = true;
TestService.MyBinder myBinder = (TestService.MyBinder) binder;
service = myBinder.getService();
Log.i("DemoLog", "ActivityB onServiceConnected");
int num = service.getRandomNumber();
Log.i("DemoLog", "ActivityB 中調用 TestService 的 getRandomNumber 方法, 結果: " + num);
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
Log.i("DemoLog", "ActivityB onServiceDisconnected");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnBindService) {
Intent intent = new Intent(this, TestService.class);
intent.putExtra("from", "ActivityB");
Log.i("DemoLog", "ActivityB 執行 bindService");
bindService(intent, conn, BIND_AUTO_CREATE);
} else if (v.getId() == R.id.btnUnbindService) {
if (isBound) {
Log.i("DemoLog", "ActivityB 執行 unbindService");
unbindService(conn);
}
} else if (v.getId() == R.id.btnFinish) {
Log.i("DemoLog", "ActivityB 執行 finish");
this.finish();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("DemoLog", "ActivityB -> onDestroy");
}
}
把 client 與 server 串起來的關鍵是 Binder。要在 Service 中支援 bindService,必須做到兩點:
1. 在 onBind() 中回傳一個 IBinder 型別的實例;
2. 這個 IBinder 必須能回傳 Service 本身,或至少把 Service 的公開方法暴露出來。最簡單明瞭的寫法就是把 Binder 做成 Service 的內部類,並在其中提供類似 getService() 的方法。
1. 建立 ServiceConnection 實例,覆寫 onServiceConnected() 與 onServiceDisconnected();
2. 把這個實例傳給 bindService()。當 Service 尚未存在時,系統會先建立 Service 實例、執行 onBind() 取得 IBinder,再把它當參數傳進 client 的 onServiceConnected()。此時把 IBinder 轉型成自己的 Binder 型別,就能直接取得 Service 實例或呼叫其公開方法;
3. 在 onServiceDisconnected() 中處理斷線後的善後工作。
只涉及 ActivityA。先按「bindService」,再按「unbindService」,輸出如下:

可以確定一件事:Service 的所有回呼都跑在主執行緒上。呼叫 bindService 時需傳入 Intent 與 ServiceConnection。由於 Service 此時還不存在,系統會先建立實例並執行 onCreate()(整個生命週期只會呼叫一次),接著執行 onBind() 並回傳 IBinder。這個 IBinder 會被系統快取,對所有 client 共享——後續其他 client 呼叫 bindService 時不會再觸發 onBind,而是直接沿用這一個。取得 IBinder 後,系統才會回呼 client 的 onServiceConnected()。
整體順序可以濃縮成:
client 執行 bindService → 若 Service 不存在,Service 執行 onCreate → 若尚未執行過 onBind,Service 執行 onBind → client 的 ServiceConnection 執行 onServiceConnected
執行 unbindService 後,該 client 解除綁定;Service 會檢查是否还有其他 client 連著,若沒有,便依序執行 onUnbind() 與 onDestroy():
client 執行 unbindService → client 與 Service 解除綁定 → Service 檢查是否還有其他 client,若沒有 → Service 執行 onUnbind → Service 執行 onDestroy
重啟 App,先按「bindService」,接著按「Finish」讓 ActivityA 直接銷毀:

結果顯示:ActivityA 的 onDestroy() 執行完之後,TestService 依序執行了 onUnbind() 與 onDestroy()。也就是說,client 銷毀時,系統會自動幫它解除綁定,效果等同在 destroy 之前先呼叫了一次 unbindService。
這次同時牽涉 ActivityA 與 ActivityB,操作步驟如下:
1. ActivityA 按「bindService」
2. ActivityA 按「start ActivityB」,切換到 ActivityB
3. ActivityB 按「bindService」
4. ActivityB 按「unbindService」
5. ActivityB 按「Finish」
6. ActivityA 按「unbindService」

逐步分析:
步驟 1:Service 實例不存在,第一次 bindService 會建立 TestService 並執行 onCreate() 與 onBind(),取得 IBinder 後傳入 ActivityA 的 onServiceConnected,此時只有一個 client。
步驟 2:切換畫面。
步驟 3:Service 已在執行中,ActivityB 呼叫 bindService 不會再次觸發 onCreate(),也不會觸發 onBind()(因為共享的 IBinder 已存在),而是直接取得既有實例並回呼 ActivityB 的 onServiceConnected。此時有兩個 client 綁定。
步驟 4:ActivityB 解除綁定。但由於 ActivityA 仍處於綁定狀態,不會觸發 onUnbind() 與 onDestroy()。這正是「僅在完全沒有 client 時才銷毀」的具體體現。
步驟 5:ActivityB 銷毀,畫面回到 ActivityA。
步驟 6:ActivityA 解除綁定,此時已無任何 client,系統先執行 onUnbind() 再執行 onDestroy(),Service 生命週期結束。
再次強調:本文所說的 client 一律指「元件」(Component),例如某個 Activity。同一個 Activity 內即使多次呼叫 bindService,對 Service 而言仍只算一個 client。

掌握「IBinder 全域共享、client 計數決定銷毀時機」這兩個核心觀念,bindService 的生命週期其實並不難理解。
Android Fragment 界面向下跳轉與逐層返回的實作方法詳解
本文示範如何在 Android 中使用 Fragment 實現介面向下一層層跳轉、並能一級級返回的效果,供大家參考。核心思路是透過自訂的返回處理介面與抽象 Fragmen
greenDAO 上手實戰:從配置、代碼生成到增刪改查全流程
最近項目裡用到了 greenDAO,順手把整個使用過程記錄下來。 一、greenDAO 是什麼 greenDAO 是對 SQLite 的封裝,讓我們能更省心地把玩 SQ
Android 自訂動畫:左右旋轉、上下翻轉與平移動畫實作
先看一下最終效果: 這裡的 GIF 是用 GifCam 錄製的,可到 https://download.csdn.net/detail/baidu_nod/762846
三款炫酷的 Android Loading 動畫組件推薦
最近突然對 Loading 動畫產生了興趣。Loading 這東西說重要也重要,說不重要也不重要——它是提升產品體驗的一個細節。如果 loading 做得好,對於那些耗時