IPC 設(shè)置死亡代理

Binder是可能以外死亡的,這往往是由于服務(wù)端進程意外停止了,這是我們需要重新連接服務(wù)。有兩種方法。

方法一

第一種方法時給Binder設(shè)置DeathReciient監(jiān)聽,當Binder死亡是,我們就會受到binderDied方法的回調(diào),在binderDied方法中我們可以重連遠程服務(wù)。
需要在Activity中進行修改

    /**
     * 設(shè)置死亡代理
     */
    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {

        @Override
        public void binderDied() {
            if (iBookManager == null) {
                return;
            }
            iBookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
            iBookManager = null;
            //重新綁定服務(wù)
            bindMyService();
        }
    };

    /**
     * 綁定服務(wù)
     */
    private void bindMyService() {
        Intent serviceIntent = new Intent(this, BookManagerService.class);
        serviceConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                iBookManager = IBookManager.Stub.asInterface(service);
                try {
                    //設(shè)置死亡代理
                    iBookManager.asBinder().linkToDeath(mDeathRecipient, 0);
                    //注冊監(jiān)聽
                    iBookManager.registerListener(iOnNewBookArrvedListener);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                iBookManager = null;
            }
        };
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

    }
方法二

在onServiceDisconnected方法中重連遠程服務(wù)

兩種方法的區(qū)別

onServiceDisconnected運行在ui線程中被回調(diào),而binderDied在客戶端的Binder線程池中被回調(diào)。所以在binderDied方法中不能訪問UI。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容