zoukankan      html  css  js  c++  java
  • Binder的非正常消亡时的重置方法

    一、原理

    当Binder非正常消亡的时候,会导致远程调用失败,这样客户端功能就会受到影响。

    解决:给Binder设置一个死亡代理,当Binder死亡时,我们就会收到通知,这个时候可以重新发起连接。

    二、制作

    1、前期准备

    客户端:MainActivity.java

      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            createService();
        }
        /*连接Service端,获取mIBookManger*/
        private void createService(){
            ServiceConnection connection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    //初始化mIBookManger
                    mIBookManager = IBookManager.Stub.asInterface(service);
                }
    
                @Override
                public void onServiceDisconnected(ComponentName name) {
    
                }
            };
            Intent intent = new Intent(this,BookService.class);
            bindService(intent,connection,BIND_AUTO_CREATE);
        }
    View Code

    Service端:BookService.java

    2、使用

    创建IBinder.DeathRecipient接口,重写其中的binderDied(),当Binder死亡时候,回调该方法。

      private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
            @Override
            public void binderDied() {
                if (mIBookManager != null){
                    //解除绑定当前接口
                    mIBookManager.asBinder().unlinkToDeath(mDeathRecipient,0);
                }
                mIBookManager = null;
    
                createService();
            }
        };

    当然解除绑定,之前还需要绑定接口

     /*连接Service端,获取mIBookManger*/
        private void createService(){
            ...(连接之前的代码)
            try {
                //绑定接口,等待回调
                mIBookManager.asBinder().linkToDeath(mDeathRecipient,0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }        
  • 相关阅读:
    制作Autorun的CD
    Sybase ASE MDA tables 装不上怎么办?
    对于TStringList.Find函数,我有话要说
    HH.exe CHM Operator Command.
    Delphi 7的一些常用的快捷键
    Explain Plan
    在Delphi中的Log
    subst windows下实用的磁盘映射工具
    Excel 2007 如何冻结多行&多列
    LinqToDataTable[转]
  • 原文地址:https://www.cnblogs.com/rookiechen/p/5382851.html
Copyright © 2011-2022 走看看