Android如何實現跨進程接口回掉

        同一個進程內實現接口回掉很簡單,這裏不作敘述,本文主要講的是跨進程的接口回掉實現方式。有一種跨進程通訊的方式就是使用AIDL,可是單純的AIDL通訊只能夠實現客戶端訪問服務端主動獲取Binder對象,若是服務端有變化沒法及時通知客戶端。如今能夠經過AIDL跨進程接口回掉來解決服務端發生變化通知客戶端的問題。java

         谷歌提供了RemoteCallbackList來實現對IInterface的管理。public class RemoteCallbackList<E extends IInterface>bash

首先定義兩個AIDL文件:

  1. ITestCallBack.aidl
    interface ITestCallBack {
        /**
         * Demonstrates some basic types that you can use as parameters
         * and return values in AIDL.
         */
        void onTagValid(in String tag);
    
    }
    複製代碼
  2. ITestInterface.aidl    在註冊和反祖冊方法中,須要傳入ITestCallBack的對象
    interface ITestInterface {
        /**
         * Demonstrates some basic types that you can use as parameters
         * and return values in AIDL.
         */
         boolean isTagValid(in String tag);
    
         void registerCallback(in String tag, in ITestCallBack callback);
    
         void unRegisterCallback(in String tag, in ITestCallBack callback);
    }複製代碼

服務端:

         建立Service,而且在service中定義RemoteCallbackList集合,實現ITestInterface.Stub,在registerCallback,和unRegisterCallback中,分別將ITestCallBack對象註冊和反註冊進RemoteCallbackList中。RemoteCallbackList提供了獲取註冊進去的IInterface對象方法。app

//其實RemoteCallbackList相似於java中{@link java.util.Observable},用來批量處理接口回調對象,
//其實若是確保只有一個客戶端會bind到這個服務,只須要保存一個IMyAidlInterfaceCallback便可。
//可是若是有多個,強烈推薦使用其實RemoteCallbackList

public void callBack() {
    if (mCallBacks == null) {
        return;
    }
    int num = mCallBacks.beginBroadcast();
    for (int i = 0; i < num; i++) {
        try {
            mCallBacks.getBroadcastItem(i).onTagValid("congratulation callback success " + tag);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    //結束後必定要使用finsh,不然下次執行beginBroadcast會拋出IllegalStateException異常
    mCallBacks.finishBroadcast();
}複製代碼

在isTagValid中能夠調用callBack方法去遍歷註冊的接口對象,也能夠當服務端有變化時主動調用callBack方法去通知客戶端,這樣就實現了服務端變化主動通知客戶端。可根據實際方法修改。ide

在service的onBind方法中,返回ITestInterface.Stub的對象便可,等待客戶端綁定服務端。ui

下面是服務端Service的代碼:this

public class TestService extends Service {

    private RemoteCallbackList<ITestCallBack> mCallBacks = new RemoteCallbackList<>();
    private String tag = "hy";

    public TestService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return iTestInterface;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    ITestInterface.Stub iTestInterface = new ITestInterface.Stub() {
        @Override
        public boolean isTagValid(String tag) throws RemoteException {
            if (tag.equals(TestService.this.tag)) {
                callBack();
                return true;
            }
            return false;
        }

        @Override
        public void registerCallback(String tag, ITestCallBack callback) throws RemoteException {
            if (null != mCallBacks && null != callback) {
                mCallBacks.register(callback);
            }
        }

        @Override
        public void unRegisterCallback(String tag, ITestCallBack callback) throws RemoteException {
            if (null != mCallBacks && null != callback) {
                mCallBacks.unregister(callback);
            }
        }
    };

    public void callBack() {
        if (mCallBacks == null) {
            return;
        }
        int num = mCallBacks.beginBroadcast();
        for (int i = 0; i < num; i++) {
            try {
                mCallBacks.getBroadcastItem(i).onTagValid("congratulation callback success " + tag);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        mCallBacks.finishBroadcast();
    }
}複製代碼

客戶端:

        客戶端首先要作的是綁定服務端,實現AIDL的通訊,在客戶端建立綁定按鈕,解綁按鈕,和主動獲取信息的通訊按鈕。在主動獲取信息的通訊按鈕中實現iTestInterface對象的isTagValid方法能夠主動去獲取服務端的信息(服務端在isTagValid方法中調用了callBack方法)。spa

客戶端代碼:code

public class MainActivity extends AppCompatActivity {

    private String tag = "hy";
    private ITestInterface iTestInterface;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iTestInterface = ITestInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            iTestInterface = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindService();
        ((Button) findViewById(R.id.buttonregister)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    iTestInterface.registerCallback(tag, new ITestCallBack.Stub() {
                        @Override
                        public void onTagValid(String tag) throws RemoteException {
                            Log.e("test", "registerCallback: " + tag);
                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        ((Button) findViewById(R.id.buttonunregister)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    iTestInterface.unRegisterCallback(tag, new ITestCallBack.Stub() {
                        @Override
                        public void onTagValid(String tag) throws RemoteException {

                        }
                    });
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        ((Button) findViewById(R.id.buttonisvalid)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    iTestInterface.isTagValid(tag);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void bindService() {
        Intent intent = new Intent();
        intent.setAction("com.example.heyang.myapplication.TestService");
        intent.setPackage("com.example.heyang.myapplication");
        boolean success = bindService(intent, connection, Context.BIND_AUTO_CREATE);
        if (success) {
            Log.e("test ", "bindService OK");
        } else {
            Log.e("test ", "bindService Fail");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unBindeService();
    }

    private void unBindeService() {
        try {
            unbindService(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
複製代碼
相關文章
相關標籤/搜索