Android 之 守护进程

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/JimTrency/article/details/79087593

之前,低版本做守护进程时,就是两个service 相互守护,但是大于5.0后,似乎就不管用了,今天我们来看看,怎么解决这个问题,多的不说,直接上代码:

首先是有业务处理的service:

public class GuardMessageService extends Service{

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    System.out.println("=====守护进程======");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(1,new Notification());
        bindService(new Intent(this, GuardService.class),connection, Context.BIND_IMPORTANT);

        return START_STICKY;
    }

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

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //建立连接
            Toast.makeText(GuardMessageService.this,"建立连接",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //连接断开了
            startService(new Intent(GuardMessageService.this,GuardService.class));
            bindService(new Intent(GuardMessageService.this, GuardService.class),connection, Context.BIND_IMPORTANT);
        }
    };

 }

2.守护的service:

public class GuardService extends Service{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new GuardAidl.Stub() {};
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(1,new Notification());
        bindService(new Intent(this, GuardMessageService.class),connection, Context.BIND_IMPORTANT);

        return START_STICKY;
    }

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

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //连接断开了
            startService(new Intent(GuardService.this,GuardMessageService.class));
            bindService(new Intent(GuardService.this, GuardMessageService.class),connection, Context.BIND_IMPORTANT);
        }
    };
}

3.为了解决5.0 以上,设置的一个service:

public class JobWakeUpService extends JobService{

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

        JobInfo.Builder jobBuilder = new JobInfo.Builder(
                1,new ComponentName(this,JobWakeUpService.class));
        jobBuilder.setPeriodic(2000);

        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(jobBuilder.build());
        return START_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {

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

        return false;
    }

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

    /**
     * 判断某个服务是否正在运行的方法
     */
    private boolean serviceAlive(String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> 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;
    }
}

最后是AndroidManifest.xml的配置:

 // JobService权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

 <service android:name=".services.GuardService"
        android:process=":guardService"/>
    <service android:name=".services.GuardMessageService"/>
    <service android:name=".services.JobWakeUpService"
        android:enabled="true"
       android:permission="android.permission.BIND_JOB_SERVICE"
     />

调用:

      //启动守护进程
            startService(new Intent(mContext, GuardMessageService.class));
            startService(new Intent(mContext, GuardService.class));
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                //必须大于5.0
                startService(new Intent(mContext,JobWakeUpService.class));
            }
展开阅读全文

没有更多推荐了,返回首页