完全参考 任玉刚老师的书籍案例案例
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服务的时候,进入设置去停止服务就可以看到回调