RemoteCallbackLIst
- 參考地址
RemoteCallbackList 是 Android SDK 中的一個類,用于幫助管理進程之間的回調。它專為進程間通信 (IPC) 場景而設計,在該場景中,應用程序的不同部分甚至不同的應用程序可能在不同的進程中運行。
以下是其關鍵功能的細分:
- 維護回調列表:您可以使用
register()
向列表注冊多個回調對象。 - 將消息傳遞給所有注冊的回調:當您在 RemoteCallbackList 上調用
broadcast()
等方法時,它將調用每個注冊的回調對象上的相應方法。 - 處理死掉的 Binder:如果托管回調的進程死亡,RemoteCallbackList 會自動從列表中刪除該回調。
使用 RemoteCallbackList 的優勢:
- 安全且高效:它處理 Binder 死亡并確保回調僅傳遞給活動的進程。
- 方便:簡化了管理多個回調的過程,避免了手動處理 Binder 死亡。
常見用例:
- 在進程之間實現事件偵聽器(例如,通知活動服務更新)。
- 在系統組件和應用程序之間傳遞回調。
其他資源:
- 官方文檔: https://developer.android.com/reference/android/os/RemoteCallbackList
- 源代碼: https://android.googlesource.com/platform/frameworks/base/+/HEAD/core/java/android/os/RemoteCallbackList.java
- CSDN 上的討論: https://blog.csdn.net/qq_28095461/article/details/135826573
RemoteCallbackList 的用途:
RemoteCallbackList 可用于在進程之間傳遞回調。這意味著您可以將一個進程中的回調注冊到另一個進程中的對象。當該對象發生更改時,它會調用回調以通知第一個進程。
這在許多情況下都很有用,例如:
- 在服務和活動之間進行通信:服務可以使用 RemoteCallbackList 通知活動其狀態已更改。
- 在不同的應用程序之間進行通信:兩個應用程序可以使用 RemoteCallbackList 相互通知事件。
使用 RemoteCallbackList 的示例:
以下是一個簡單示例,演示如何在兩個活動之間使用 RemoteCallbackList 進行通信:
MyService.java:
public class MyService extends Service {private RemoteCallbackList<MyCallback> mCallbacks = new RemoteCallbackList<>();@Overridepublic IBinder onBind(Intent intent) {return new MyBinder();}public void doSomething() {// Notify all registered callbacks.for (MyCallback callback : mCallbacks) {callback.onSomethingChanged();}}public class MyBinder extends Binder {public MyService getService() {return MyService.this;}public void registerCallback(MyCallback callback) {mCallbacks.register(callback);}public void unregisterCallback(MyCallback callback) {mCallbacks.unregister(callback);}}
}
MyActivity.java:
public class MyActivity extends AppCompatActivity implements MyCallback {private MyService mService;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// Bind to the service.Intent intent = new Intent(this, MyService.class);bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);}@Overridepublic void onSomethingChanged() {// Do something in response to the change.Log.d("MyActivity", "Something changed!");}private ServiceConnection mServiceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {mService = ((MyService.MyBinder) service).getService();// Register the callback with the service.mService.registerCallback(MyActivity.this);}@Overridepublic void onServiceDisconnected(ComponentName name) {mService = null;// Unregister the callback with the service.mService.unregisterCallback(MyActivity.this);}};
}
在這個示例中,MyService
是一個簡單的服務,它提供一個 doSomething()
方法來通知所有注冊的回調。MyActivity
是一個活動,它綁定到 MyService
并注冊為回調。當 MyService
調用 doSomething()
時,MyActivity
中的 onSomethingChanged()
方法將被調用。
參考地址
chatgpt