通过AIDL与服务端进行通信时,意外发生服务终止的解决方法。
1、设置服务死亡代理deathRecipient
private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { isConnection = true; sceneModeAPI = ISceneModeAPI.Stub.asInterface(iBinder); try { sceneModeAPI.asBinder().linkToDeath(deathRecipient, 0); } catch (RemoteException e) { e.printStackTrace(); } LogUtils.e(TAG, "mode control service connection successful"); }
2、在代理对象中重连服务
/** * 重连服务 */ private void reconnectService() { Log.d(TAG, "mode control service binder died"); sceneModeAPI.asBinder().unlinkToDeath(deathRecipient, 0); ThreadUtils.runOnUiThreadDelayed(this::bindServiceInvoked, 1000); } /** * 设置服务死亡代理 */ IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() { @Override public void binderDied() { isConnection = false; reconnectService(); } }; /** * 绑定服务 */ public void bindServiceInvoked() { Intent intent = new Intent(); intent.setAction(SERVICE_ACTION); intent.setPackage(SERVICE_PACKAGE); isConnection = context.bindService(intent, connection, Context.BIND_AUTO_CREATE); }
标签:服务,AIDL,void,代理,死亡,intent,deathRecipient From: https://www.cnblogs.com/suiyilaile/p/16635945.html