进程保活:双进程守护 + JobScheduler

创建 src/main/aidl 文件夹,在其中新建 .aidl 文件

进程保活:双进程守护 + JobScheduler_第1张图片
创建好后rebuild一下,会自动生成ProcessConnection.java文件
// ProcessConnection.aidl
package com.zkt.nhdz;

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

interface ProcessConnection {

}

1. 使用:在 MainActivity 的 onCreate() 里,

// JobScheduler 
  startService(new Intent(this, JobWakeUpService.class));
// 双进程守护
  startService(new Intent(this, MessageService.class));
  startService(new Intent(this, GuardService.class));

2. 双进程守护 —— 守护进程

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.widget.Toast;

import com.zkt.nhdz.ProcessConnection;

/**
 * 守护进程
 */
public class GuardService extends Service {

    private final int GuardId = 1;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //提高进程的优先级
        startForeground(GuardId, new Notification());

        //绑定建立连接
        bindService(new Intent(this, MessageService.class), mServiceConnection, Context.BIND_IMPORTANT);

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new ProcessConnection.Stub() {
        };
    }


    ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(GuardService.this, "与Message建立连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            startService(new Intent(GuardService.this, MessageService.class));
            //绑定建立连接
            bindService(new Intent(GuardService.this, MessageService.class), mServiceConnection,
                    Context.BIND_IMPORTANT);

        }
    };
}

3. 正常写业务逻辑的服务进程

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.zkt.nhdz.ProcessConnection;

/**
 * Created by zkt on 2018-4-19.
 * Description:
 */

public class MessageService extends Service {

    private final int MessageId = 1;

    @Override
    public void onCreate() {
        //        new Thread(new Runnable() {
        //            @Override
        //            public void run() {
        //                while (true) {
        //                    try {
        //                        Thread.sleep(2000);
        //                        Log.e("Message", "等待接受消息");
        //                    } catch (InterruptedException e) {
        //                        e.printStackTrace();
        //                    }
        //                }
        //            }
        //        }).start();
        Log.e("MessageService", "启动啦");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("MessageService", "onStartCommand 执行啦执行啦");

        //提高进程的优先级
        startForeground(MessageId, new Notification());
        //绑定建立连接
        bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT);

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MessageBind();
    }

    private class MessageBind extends ProcessConnection.Stub {

    }

    ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(MessageService.this, "与Guard建立连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            startService(new Intent(MessageService.this, GuardService.class));
            //绑定建立连接
            bindService(new Intent(MessageService.this, GuardService.class), mServiceConnection,
                    Context.BIND_IMPORTANT);

        }
    };
}

4. 接下来是JobScheduler轮询,判断服务是否被干掉


import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import java.util.List;

/**
 * Created by zkt on 2018-4-25.
 * Description: 5.0以上的
 */

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class JobWakeUpService extends JobService {
    private final int jobWakeUpId = 1;
    private JobScheduler jobScheduler;
    private JobInfo.Builder builder;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("JobWakeUpService", "onStartCommand执行啦");
        builder = new JobInfo.Builder(jobWakeUpId, new ComponentName(this, JobWakeUpService.class))
                .setMinimumLatency(4000)
                .setPersisted(true);
        jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(builder.build());
        return START_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        // 如果杀死了启动 轮询onStartJob
        Log.e("JobWakeUpService", "onStartJob 执行啦执行啦");

        //判断服务有没有在运行
        boolean messageServiceAlive = isServiceRunning(MessageService.class.getName());
        if (!messageServiceAlive) {
            startService(new Intent(this, MessageService.class));
        }

        //执行任务
        jobScheduler.schedule(builder.build());

        //第二个参数,类似于onStopJob的返回值,是否需要重新执行
        jobFinished(params, false);

        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    /**
     * 判断某个服务是否在运行
     *
     * @param serviceName
     * @return
     */
    private boolean isServiceRunning(String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

}

你可能感兴趣的:(进程保活:双进程守护 + JobScheduler)