AIDL基本使用4—- 4、linkToDeath和unlinkToDeath

完全参考 任玉刚老师的书籍案例案例

Binder运行在服务端进程,如果服务端进程由于某些原因异常终止,这个时候我们到服务端的Binder连接断裂,会导致我们的远程调用失败。Binder提供了两个配对的方法linkToDeath和unlinkToDeath,通过linkToDeath我们可以给Binder设置一个死亡代理,当Binder死亡时,我们会收到通知,这个时候我们就可以重新发起连接请求从而恢复连接。

package com.ucoupon.client2;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.ucoupon.myservice.IMyAidlInterface;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //连接管理
        Myconnect myconnect = new Myconnect();


        //意图
        Intent intent = new Intent();

//        intent.setPackage("com.ucoupon.myservice");
        intent.setClassName("com.ucoupon.myservice", "com.ucoupon.myservice.MyService");

        startService(intent);

        //开始绑定服务
        bindService(intent, myconnect, BIND_AUTO_CREATE);
    }

    private static final String TAG = "client2";
    //死亡接受者
    IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            if (iMyAidlInterface != null) {
                //注销监听和回收资源
                iMyAidlInterface.asBinder().unlinkToDeath(this, 0);
                iMyAidlInterface = null;
            }
        }
    };
    private IMyAidlInterface iMyAidlInterface;

    class Myconnect implements ServiceConnection {


        //连接的成功的时候回调
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected() called with: name = [" + name + "], service = [" + service + "]");


            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);

            try {
                //连接死亡监听
                service.linkToDeath(deathRecipient, 0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            try {
                String msg = iMyAidlInterface.basicTypes(1, "客户端传入的");
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            //解绑服务
//            unbindService(myconnect);
        }

        //断开连接的时候回调
        @Override
        public void onServiceDisconnected(ComponentName name) {

            Log.d(TAG, "onServiceDisconnected() called with: name = [" + name + "]");
        }
    }
}

tip:大家bind服务的时候,进入设置去停止服务就可以看到回调

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值