Android bindService

  • bindService是异步的,方法调用最好是放在OnServiceConnected
  • 实现ServiceConnection.
    • 你的实现必须重写两个回调方法:
      • onServiceConnected()
        • 系统调用这个来传送在service的onBind()中返回的IBinder.
        • OnServiceDisconnected()
        • Android系统在同service的连接意外丢失时调用这个.比如当service崩溃了或被强杀了.当客户端解除绑定时,这个方法不会被调用
  • google开源的android系统有强杀一个app的方法,如下:
 private void KillRTMPProcess() {
        ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        try {
            Method method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
            method.invoke(manager, RTMP_APP);

            iThirdPartyCallback = null;
            callThirdParty = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    • 此方法需要权限
      <uses-permission android:name="android.permission.FORCE_STOP_PACKAGES"/>

如果在客户端调用杀死远程服务app可以使用以上方法,这时就会走onServiceDisconnected

  • 最好在onServiceConnected里面设置死亡监听,这样服务意外死亡就会收到监听

  

    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            Log.i(TAG, "binderDied: ");
            if (callThirdParty == null){
                Log.i(TAG, "binderDied: rmeote==null");
                return;
            }
            callThirdParty.asBinder().unlinkToDeath(this,0);
            callThirdParty = null;
            bindService(intent,serviceConnection,BIND_AUTO_CREATE);
        }
    };
 ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected: ");
            callThirdParty = IThirdPartyCase.Stub.asInterface(service);
            try {
                service.linkToDeath(mDeathRecipient,0);
                callThirdParty.registeCallback(iThirdPartyCallback);

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

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected: ");
          

        }
    };
    •  意外死亡 重新绑定服务在binderdied方法里进行(这个方法运行Binder线程不是客户端的UI线程)
  • 解绑的时候也要解除死亡监听、remotecallback
    if (callThirdParty != null && callThirdParty.asBinder().isBinderAlive()){
                try {
                    callThirdParty.asBinder().unlinkToDeath(mDeathRecipient,0);
                    callThirdParty.unregisteCallback(iThirdPartyCallback);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            unbindService(serviceConnection);

 

posted on 2019-07-26 11:07  endian11  阅读(380)  评论(0编辑  收藏  举报

导航