標籤:
通常情況下 , 公司需要讓自己的產品在使用者的手機中儘可能存活長的時間,包括不受大數字,手動清理後台等情況的影響。這裡給出一種方式 就是 雙進程守護;
模型:
兩個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互相監聽,互相守護。
關於Android 應用保活