Binders 是Android IPC 的實現 主要用於不同Process 通訊 並且Binder基於 遠程過程呼叫(Remote Procedure Call, RPC) 可以去調用另一個process 的物件的方法 就像這些物件好像是跑在本地一樣
同一個應用程式不同進程 就算Remote
RPC 模型: Clinet 透過blinder 調用遠程服務方法 並加請求序列化(marshalling)傳給目標Process 並等待回傳結果
Service 通常會使用Binder 來通訊 Service 會根據AIDL(Android Interface Definition Language) 檔案來定義介面 來標準化 方法 參數與回傳值 總而言之 Service 提供實際功能 而binder 負責在clinet 與 service 之間傳遞Request 和 response
定義 可被遠程調用方法 例如add()
Calculator.aidl
interface ICalculator {
int add(int a, int b);
}
創建Services 和 interface
public class CalculatorService extends Service {
private final ICalculator.Stub binder = new ICalculator.Stub() {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
接下來 我們要bind到遠程Process 來實現IPC
連到遠程的serices
// Connecting to the remote service
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
calculatorService = ICalculator.Stub.asInterface(service);
performCalculations();
}
...
};
綁定Remote service
// Binding to the remote service
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example.calculatorservice", "com.example.calculatorservice.CalculatorService"));
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
調用遠程Service 方法
// Calling the methods
private void performCalculations() {
if (calculatorService == null) {
return;
}
try {
int additionResult = calculatorService.add(10, 5);
// Use the results as needed, e.g., display them in the UI
// ...
} catch (RemoteException e) {
e.printStackTrace();
}
}
如果Service 運行在與主進程不同的進程中 需要再AndroidManifest.xml 中 設置 android:process 屬性 並指定該Service process 名稱
<manifest ...>
<application ...>
<service
android:name=".MyService"
android:process=":remote" />
</application>
</manifest>
android:process=":remote" 指定服務在不同的過程中運行