一行程式碼實現Android的跨程序呼叫與通訊
年後第一發,帶來一款更簡潔方便的Android程序通訊方案。看了網上太多的Binder以及跨程序講解,最後回到我們自己來進行跨程序通訊時發現還是相當繁瑣,定義aidl、定義Service、bindService
等一系列操作搞得頭都大了。
CmProcess
可簡單輕鬆解決程序間通訊問題,幾行程式碼搞定,任意程序隨時註冊服務,隨時同步獲取服務以及支援跨程序的事件匯流排。
介紹
CmProcess 更方便更簡潔的Android程序通訊方案,無需進行bindService()操作,不用定義Service,也不需要定義aidl。 支援IPC級的Callback,並且支援跨程序的事件匯流排。可同步獲取服務。採用面向介面方式進行服務註冊與呼叫,服務呼叫方和使用者完全解耦。
接入
1. 在全域性build裡新增倉庫
allprojects { repositories { ...... maven { url 'https://jitpack.io' } } }
2. 在app的build裡新增依賴
dependencies { implementation 'com.github.zhangke3016:CmProcess:1.0.3' }
使用
1. 在Application的attachBaseContext方法中初始化
@Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); VCore.init(base); }
2. 定義對外提供服務功能的介面和實現
如果註冊本地服務,引數以及回撥介面沒有限制;
如果註冊遠端服務,引數型別必須為基本資料型別或者可序列化型別(serializable/parcelable),並且非同步回撥介面需要使用提供的'IPCCallback`。
public interface IPayManager { String pay(int count); //遠端服務呼叫,非同步回撥介面需要使用提供的'IPCCallback`。 String pay(int count, IPCCallback callBack); }
3. 註冊或者反註冊服務,可在任意程序呼叫;註冊的程序本地服務需要在本程序取消註冊
//註冊本地 + 遠端服務 VCore.getCore().registerService(IPayManager.class, this); //取消註冊本地 + 遠端服務 VCore.getCore().unregisterService(IPayManager.class); //註冊本地服務 VCore.getCore().registerLocalService(IPayManager.class, this); //取消註冊本地服務 VCore.getCore().unregisterLocalService(IPayManager.class);
4. 可在任意程序通過介面型別獲取服務呼叫
IPayManager service = VCore.getCore().getService(IPayManager.class); //獲取本地服務 //IPayManager service = VCore.getCore().getLocalService(IPayManager.class); //注意:如果服務未註冊時,service為null if(service != null){ //同步呼叫. String message = service.pay(5000); //非同步回撥. 推薦使用提供的 BaseCallback 已將回調結果切換至主執行緒 service.pay(5000, new BaseCallback() { @Override public void onSucceed(Bundle result) { //Main thread 回撥結果在主執行緒 } @Override public void onFailed(String reason) { //Main thread } }); //或者 service.pay(5000, new IPCCallback.Stub() { @Override public void onSuccess(Bundle bundle) throws RemoteException { // binder thread } @Override public void onFail(String s) throws RemoteException { } }) }
5. 事件的釋出與訂閱
//訂閱事件可在任意程序的多個位置訂閱 VCore.getCore().subscribe("key", new EventCallback() { @Override public void onEventCallBack(Bundle event) { //main thread String name = event.getString("name"); Log.e("TAG", "onEventCallBack: " + name + " " + (Looper.myLooper() == Looper.getMainLooper())); } }); //釋出事件釋出事件後 多個程序註冊的EventCallback會同時回撥: Bundle bundle = new Bundle(); bundle.putString("name", "DoDo"); VCore.getCore().post("key",bundle); //取消訂閱 VCore.getCore().unsubscribe("key");