Binder 应用于C/S通信中,有时候Server可能需要知道Client进程是否存在,当Client挂掉后,Server可以及时清理资源。
利用这种机制,同样可以实现简单的程序守护,当Client崩溃后,Server帮助重启Client程序。
守护程序
守护程序开放一个Service,提供给被守护程序调用
- AIDL
package com.example.guardapp;
import android.os.IBinder;
interface IGuardService {
void attachBinder(IBinder token);
}
- Service
public class GuardService extends Service {
private static final String TAG = "GuardService";
private static final String MAIN_APP_PACKAGE = "com.example.mainapplciation";
private static final String MAIN_MAIN_ACTIVITY = "com.example.mainapplciation.MainActivity";
private IGuardService.Stub mStub = new IGuardService.Stub() {
@Override
public void attachBinder(IBinder token) throws RemoteException {
//客户端注册死亡讣告
token.linkToDeath(recipient, 0);
}
};
private IBinder.DeathRecipient recipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
//侦听到客户端死亡,重启客户端主程序
restartMainApp();
}
};
private void restartMainApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(MAIN_APP_PACKAGE, MAIN_MAIN_ACTIVITY);
intent.setComponent(cn);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public IBinder onBind(Intent intent) {
return mStub;
}
}
被守护程序
主程序即被守护程序,只要调用远程的GuardService接口即可。
//客户端Binder
private Binder mBinder = new Binder();
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IGuardService guardService = IGuardService.Stub.asInterface(service);
try {
guardService.attachBinder(mBinder);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
private void bindGuardService() {
Intent intent = new Intent();
intent.setPackage(GUARD_APP_PACKAGE);
intent.setAction(GUARD_SERVICE_ACTION);
bindService(intent, mConnection, BIND_AUTO_CREATE);
}
测试
使用adb kill 杀掉主程序,观察主程序是否重启。
示例
查看demo