Android进程保活 --- 守护进程(code)

1、守护进程:一个在后台运行并且不受任何终端控制的进程。可以用来给其他应用拉起,保活。

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class AppWatcherService extends Service {
    static final String TAG = "AppWatcherService";
    private final static boolean DEBUG = "eng".equals(Build.TYPE) || "userdebug".equals(Build.TYPE);

    private static final int RESTART_BIND_INTERVAL = 1000;
    private static final int MAX_RETRY_COUNT = 10;

    private static final String APP_PACKAGE_NAME = "com.android.app";
    private static final String APP_INTERFACE_NAME = "com.android.app.IRegisterReceiverService";
    private static final String APP_SERVICE_NAME  = "com.android.app.RegisterReceiverService";

    private Context mContext;
    private Handler mHandler = new Handler();
    private int mBindRetryCount = 0;

    private Runnable mRebindFunc = new Runnable() {
        @Override
        public void run() {
            reBindService();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (DEBUG) Log.d(TAG, "onStartCommand");
        if (isExistAppPackage(APP_PACKAGE_NAME)) {
            Intent intent1 = new Intent(APP_INTERFACE_NAME);
            intent1.setPackage(APP_PACKAGE_NAME);
            intent1.setComponent(new ComponentName(APP_PACKAGE_NAME,APP_SERVICE_NAME));
            mContext.bindService(intent1, mServiceConnection, BIND_AUTO_CREATE);
        }

        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private IBinder mService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            try {
                if (DEBUG) Log.d(TAG, "onServiceConnected : " + className.getPackageName() + " " + className.getClassName());
                mService = service;
            } catch (Exception e) {
                Log.e(TAG, "onServiceConnected Exception : " + e);
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            try {
                if (DEBUG) Log.d(TAG, "onServiceDisconnected : " + className.getPackageName() + " " + className.getClassName());
                mService = null;
                unbindService(mServiceConnection);
                mHandler.postDelayed(mRebindFunc, RESTART_BIND_INTERVAL);
            } catch (Exception e) {
                Log.e(TAG, "onServiceDisconnected : " + e);
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void reBindService() {
        if (DEBUG) Log.d(TAG, "reBindService");
            if (isExistAppPackage(APP_PACKAGE_NAME)) {
            Intent intent = new Intent(APP_INTERFACE_NAME);
            intent.setPackage(APP_PACKAGE_NAME);
            bindAppService(intent);
        }
    }

    private void bindAppService(Intent intent) {
        if (DEBUG) Log.d(TAG, "Bind Intent : " + intent);
        if (mContext.bindService(intent, mServiceConnection, BIND_AUTO_CREATE)) {
            //如果已经绑定了服务,重新连接
            if (DEBUG) Log.d(TAG, "BindService Success");
            mBindRetryCount = 0;
            mHandler.removeCallbacks(mRebindFunc);
        } else {
            //如果绑定失败,每间隔1秒进行10次重试
            mBindRetryCount++;
            if (DEBUG) Log.d(TAG, "Retry Count : " + mBindRetryCount);
            if (mBindRetryCount < MAX_RETRY_COUNT) {
                if (DEBUG) Log.d(TAG, "Bind Service Failed. Retry in 1 second.");
                mHandler.postDelayed(mRebindFunc, RESTART_BIND_INTERVAL);
            } else {
                mBindRetryCount = 0;
                if (DEBUG) Log.d(TAG, "Bind Service was Retried a Maximum.");
            }
        }
    }

    public boolean isExistAppPackage(String packageName) {
        //判断app包是否存在
        boolean ret = false;
        PackageManager pm = getApplicationContext().getPackageManager();
        try {
            pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            ret = true;
        } catch (PackageManager.NameNotFoundException e) {
            if (DEBUG) Log.w(TAG, "App Package Not Found:"+packageName);
            ret = false;
        }
        return ret;
    }
}

可以接收开机广播以后,就启动这个service来绑定要被保活的应用

2、被守护的进程

①创建一个aidl,用于进程间通信

interface IRegisterReceiverService {
}

②AndroidManifest.xml中注册被绑定的service

        <service android:name="com.android.alarmclock.RegisterReceiverService"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:exported="true">
            <intent-filter>
                <action android:name="com.android.alarmclock.IRegisterReceiverService" />
            </intent-filter>
        </service>

③继承JobIntentService

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;

import android.support.v4.app.JobIntentService;

public class RegisterReceiverService extends JobIntentService {

    private final static String TAG = "RegisterReceiverService ";

    private final static int REGISTER_RECEIVER_ID = ;

    private final IBinder mBinder = new RegisterReceiverServiceBinder();

    private final IRegisterReceiverService.Stub mRegisterReceiverServiceBinder = new IRegisterReceiverService.Stub() {
    };

    public class RegisterReceiverServiceBinder extends Binder {
        public RegisterReceiverService getRegisterReceiverServiceBinder() {
            return RegisterReceiverService.this;
        }
    }

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, RegisterReceiverService.class, REGISTER_RECEIVER_ID, work);
    }

    @Override
    public void onHandleWork (Intent intent) {
        LogUtils.v("RegisterReceiverService Call onHandleWork");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.d(TAG + "onCreate()");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        LogUtils.d(TAG + "onStart()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = "";
        if(intent != null) {
            action = intent.getAction();
            action = action == null ? "" : action;
        }

        LogUtils.d(TAG + "onStartCommand() action=" + action );
        //可以在这里进行拉起进程后的操作

        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogUtils.d(TAG + "onBind()");

        String action = "";
        if(intent != null) {
            action = intent.getAction();
            action = action == null ? "" : action;
        }
        //可以在这里进行拉起进程后的操作

        return mBinder;
    }

    @Override
    public void onDestroy() {
        LogUtils.d(TAG + "onDestroy()");
        unregisterReceiver(mAlarmInitReceiver);

        super.onDestroy();
    }
}

此方法可以守护多个进程,启动多个进程的service即可

猜你喜欢

转载自blog.csdn.net/m0_50408097/article/details/127924979