Binder 讣告应用于进程守护

本文探讨了如何利用Binder在Android系统中实现进程守护,当Client进程崩溃时,Server能够检测并帮助重启Client,确保服务的连续性。通过设置守护Service和使用AIDL进行通信,详细介绍了守护和被守护程序的实现,并提供了测试方法和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值