进程守护_学习笔记
为什么需要进程守护
- 360、应用宝等一键加速功能通过遍历进程来kill程序
- 手机内存不足自动回收进程
- 进程保活的一种:进程守护
进程守护的原理
- 我们可以让APP有两个服务进程,彼此监听状态,如果一个进程被kill掉了,另一个立马将其唤醒。
进程守护的实现
创建两个服务,一个主服务,一个守护服务
MainActivity中,程序一启动,两个服务也立即启动
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService(new Intent(this, MainService.class)); startService(new Intent(this, GuardService.class)); }
设置使守护服务的进程与主进程不一样
<service android:label="MainService" android:name=".MainService" android:enabled="true" android:exported="true" /> <service android:label="GuardService" android:process="com.guard" android:name=".GuardService" android:enabled="true" android:exported="true"/>
共用一个binder,跨进程通信AIDL
新建文件夹aidl和java目录同级,建包,包名与java下的包名一致,新建AIDL文件。然后make一下项目,刷新。
package com.tupobi.testguardprocess; interface IGuardAidlInterface { String getServiceTag(); }
提升进程等级,前台服务
重写MainService的onStartCommand()方法
@Override public int onStartCommand(Intent intent, int flags, int startId) { Notification.Builder builder = new Notification.Builder(this); builder.setAutoCancel(true); builder.setTicker("ticker ticker"); builder.setContentText("content text"); builder.setDefaults(Notification.DEFAULT_SOUND); startForeground(110, builder.getNotification()); return super.onStartCommand(intent, flags, startId); }
两个服务互相绑定,以MainService为例
private Intent mIntent; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { } /** * 绑定断开(GuardService跪了),这是要监听的位置,一旦断开就重新绑定 * @param componentName */ @Override public void onServiceDisconnected(ComponentName componentName) { MainService.this.startService(new Intent(MainService.this, GuardService.class)); MainService.this.bindService(mIntent, mConnection, Context.BIND_IMPORTANT); } };
@Override public void onCreate() { super.onCreate(); mIntent = new Intent(this, GuardService.class); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { bindService(mIntent, mConnection, Context.BIND_IMPORTANT); ... return super.onStartCommand(intent, flags, startId); }
Binder类继承AIDL Stub
@Override public IBinder onBind(Intent intent) { LogUtil.e("MainService Pid == " + Process.myPid()); return new MyBinder(); } public class MyBinder extends IGuardAidlInterface.Stub { @Override public String getServiceTag() throws RemoteException { return "MainService Pid == " + Process.myPid(); } }
GuardService反之亦然
测试:
- 手动kill服务:两个服务会相互唤醒
- 360清理:清掉了,可能我这个手机就是360系统的手机缘故..
- 应用宝:没清掉,但是360把应用宝也清掉了
- 360:在我这个系统下,没有清不掉的软件….