編輯:Android 開發實例
當一個 Activity 綁定到某個 Service 上時,Activity 就持有了該 Service 實例的引用,可以直接調用正在運行的 Service 所暴露的方法。這與單純的 startService 不同:後者只下達一次意圖,前者建立的是一條可以雙向通信的通道。
綁定的基礎是 Service 提供一個 IBinder。通常的做法是定義一個繼承 Binder 的内部類,並在它的方法裡返回 Service 自身:
private final IBinder binder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
連接的過程由 ServiceConnection 承擔。實現這個接口並重寫兩個回調:連接建立時能拿到 Service 的引用,連接意外斷開時則把引用清空。
// Reference to the service
private MyService serviceBinder;
// Handles the connection between the service and activity
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// Called when the connection is made.
serviceBinder = ((MyService.MyBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// Received when the service unexpectedly disconnects.
serviceBinder = null;
}
};
調用 bindService,傳入一個指向目標 Service 的 Intent(顯式或隱式均可)以及上面實現好的 ServiceConnection 實例。第三個參數通常用 Context.BIND_AUTO_CREATE,表示在沒有實例時自動創建:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Bind to the service
Intent bindIntent = new Intent(MyActivity.this, MyService.class);
bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
}
一旦 Service 對象就位,就能在 onServiceConnected 中透過 serviceBinder 訪問它的公共方法與屬性。
Android 應用的進程之間通常不共享內存,但在某些場景下,你的應用確實需要與跑在其他應用進程中的 Service 交互。此時可以借助 AIDL 生成跨進程的 Binder 存根,讓綁定關係跨越進程邊界——這也是系統服務能被各個應用調用的基礎。
Android 應用調試必備命令與實戰分析
寫代碼時我們習慣用斷點單步跟蹤,但上線之後遇到的問題往往沒那麼客氣:CPU 佔用莫名飆高、內存緩慢洩露、某個頁面偶發卡死……這些問題無法靠調試器復現,只能依靠系統日誌與性
Android 實現拍照、相冊選圖並裁剪圖片的完整方案
「更換頭像」幾乎是每個 App 的必備功能,而它背後往往涉及拍照、從相冊選圖、裁剪等一系列操作。本文將帶你封裝一個可複用的 PictureSelectFragment,把
Android 檔案選擇器實作教學
檔案選擇器的用途 Android 檔案選擇器常用於讓使用者瀏覽 SD 卡或內部儲存空間,並選取特定檔案。它的概念類似傳統桌面平台的 OpenFileDialog,重點在於
Android 音訊播放實作:MediaPlayer 與播放控制
MediaPlayer 可用來播放 raw 或指定來源的音訊。建立物件後,即可控制播放、暫停與跳轉。 MediaPlayer mediaPlayer = MediaPla