進程保活之雙進程守護

雙進程守護場景:home鍵,系統應用管理,直接殺死進程,進程仍然處於運行狀態;
適用手機類型:50%的手機。
雙進程守護原理:
進程A 進程B
刪除A,同時創建B
刪除B,同時創建A
前提相關知識:
1、Service分類:一種localService 也就是普通的Service;另一種是RemoteService,遠程服務,也就是我們常說的AIDL,它是由IPC引進的一種鏈接兩個進程,兩個app的技術;
2、AIDL使用模式:
①定義AIDL接口;
②爲遠程服務實現對應的stub;
③將服務暴露給客戶程序;
代碼實現:
一、創建IServiceAidlInterface.aidl

// Declare any non-default types here with import statements

interface IServiceAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
}

二、創建本地LocalService

public class LocalService extends Service {
    private static String TAG = "LocalService";
    LocalServiceBinder localBinder;
    LocalServiceConnection localCnn;
    private int count = 0;


    @Override
    public void onCreate() {
        super.onCreate();
        if (localBinder == null) {
            localBinder = new LocalServiceBinder();
        }
        localCnn = new LocalServiceConnection();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startTime();
        Notification.Builder builder = new Notification.Builder(this);
        builder.setDefaults(Notification.DEFAULT_SOUND);
        builder.setContentTitle("Xiaoke Wang");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentInfo("info");
        builder.setWhen(System.currentTimeMillis());
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pi);
        //將serviceprocess提高到foreground process 優先級
        startForeground(startId, builder.build());
        //確保後臺運行
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return localBinder;
    }

    /**
     * 暴露外部接口
     */
    class LocalServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        /**
         * 當服務斷開連接時調用,本地服務斷開時創建另一個服務
         * @param componentName
         */
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(TAG, "onServiceDisconnected");
            LocalService.this.startService(new Intent(LocalService.this, RemoteService.class));
            LocalService.this.bindService(new Intent(LocalService.this, RemoteService.class), localCnn, Context.BIND_IMPORTANT);
        }
    }

    /**
     * 爲遠程服務實現對應的stub
     */
    class LocalServiceBinder extends IServiceAidlInterface.Stub {

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
            Log.d(TAG, "basicTypes");
        }
    }

三、創建RemoteService:

public class RemoteService extends Service {
    private static final String TAG = "RemoteService";
    RemoteServiceBinder remoteBinder;
    RemoteServiceConnection remoteCnn;
    private int count=0;


    @Override
    public void onCreate() {
        super.onCreate();
        if (remoteBinder ==null){
            remoteBinder =new RemoteServiceBinder();
        }
        remoteCnn =new RemoteServiceConnection();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return remoteBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startTime();
        Notification.Builder builder=new Notification.Builder(this);
        builder.setDefaults(Notification.DEFAULT_SOUND);
        builder.setContentTitle("Xiaoke Wang");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentInfo("info");
        builder.setWhen(System.currentTimeMillis());
        PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
        builder.setContentIntent(pi);
        //將serviceprocess提高到foreground process 優先級
        startForeground(startId,builder.build());
        return START_STICKY;
    }

    /**
     * 暴露外部接口
     */
    class RemoteServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(TAG,"onServiceDisconnected");
            RemoteService.this.startService(new Intent(RemoteService.this,LocalService.class));
            RemoteService.this.bindService(new Intent(RemoteService.this,LocalService.class),remoteCnn, Context.BIND_IMPORTANT);
        }
    }

    /**
     * 爲遠程服務實現對應的stub
     */
    class RemoteServiceBinder extends IServiceAidlInterface.Stub {


        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
            Log.d(TAG, "basicTypes");
        }
    }

四、清單文件配置:

   <service
            android:name=".LocalService"
            android:enabled="true"
            android:exported="true" />
        <service
            android:name=".RemoteService"
            android:enabled="true"
            android:exported="true"
            android:process=":remote"/>

五、MainAct開啓服務:

  startService(new Intent(this,LocalService.class));
        startService(new Intent(this,RemoteService.class));

ok項目結束,相關源碼,請留下郵箱。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章