关于Android 应用保活

 通常情况下 , 公司需要让自己的产品在用户的手机中尽可能存活长的时间,包括不受大数字,手动清理后台等情况的影响。这里给出一种方式 就是 双进程守护;

  模型如图所示:

    

   两个service通过aidl的方式 建立一种ipc通信,即在两个service的OnstartCommand方法中通过aidl的方式去bind对方;

  例如在s1中:

    

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        this.bindService(new Intent(this , LocalService2.class) , conn , Context.BIND_IMPORTANT);
        return START_STICKY;
    }

   在Onbind中:

   @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return myBinder;
    }

而MyBinder则是aidl的具体实现:

    private class MyBinder extends IProcessConnection.Stub {


        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public void getProcessName() throws RemoteException {

            Log.i("process" , "LocalService1");

        }
    }

 这样就在两个serivce建立起了连接,而通过conn这个ServiceConnection来监听连接的情况,是否断开,断开则表示有一方被杀死

    private class MyConnection extends ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

在断开时会回调onServiceDisconnected 这个方法,在里面重新启动另一个serivce并bind他就可以保证两个service互相监听,互相守护。

原文地址:https://www.cnblogs.com/yjpjy/p/5794794.html