Android 5.0+ JobService 的使用

1、新建一个Service继承 JobService

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyJobService extends JobService {

    private int mJobId = 0x00200;
    private final long requestInterval = 5*60*1000;//间隔多久调用一次
    private Context mContext;
    @Override
    public void onCreate() {
        super.onCreate();
        this.mContext = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        scheduleJob(getJobInfo());
        return START_NOT_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        KLog.a("JobService onStartJob");
        new MonitorAsyncTask().execute(jobParameters);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        KLog.a("JobService onStopJob");
        scheduleJob(getJobInfo());
        return false;
    }

    //将任务作业发送到作业调度中去
    public void scheduleJob(JobInfo t) {
        JobScheduler tm = null;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            tm = getSystemService(JobScheduler.class);
        }else{
            tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        }
        if(tm != null) {
            tm.cancel(mJobId);
            tm.schedule(t);
        }
    }


    public JobInfo getJobInfo(){

        //代表一个任务 使用建造者模式建造
        JobInfo jobInfo;
        // Android7上,设置周期执行时间,会强制按照getMinPeriodMills阈值执行,此时设置任务执行最小时间间隔解决该问题
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            jobInfo = new JobInfo.Builder(mJobId, new ComponentName(this, MyJobService.class))
                    .setBackoffCriteria(requestInterval,JobInfo.BACKOFF_POLICY_LINEAR)
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                    .setMinimumLatency(requestInterval)
                    .setOverrideDeadline(requestInterval)
                    .setPersisted(true)
                    .build();
        }else{
            jobInfo = new JobInfo.Builder(mJobId, new ComponentName(this, MyJobService.class))
                    .setBackoffCriteria(requestInterval, JobInfo.BACKOFF_POLICY_LINEAR)//设置线性重试策略
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //设置网络类型
                    .setPeriodic(requestInterval) //设置执行周期
                    .setPersisted(true)//设置重启后任务是否保留
                    .build();
        }
        return jobInfo;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent();
        intent.setClass(this,MyJobService.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startService(intent);
    }

    //AsyncTask处理耗时操作
    private class MonitorAsyncTask extends AsyncTask {
        private JobParameters mJobParameters;
        /**
         *
         * @param jobParameters The parameters of the task.
         * @return A result, defined by the subclass of this task.
         * @see #onPreExecute()
         * @see #onPostExecute
         * @see #publishProgress
         */
        @Override
        protected String doInBackground(JobParameters... jobParameters) {
            mJobParameters = jobParameters[0];
            ..... 耗时操作
            return null;
        }
        //完成之后的处理工作
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                //如果不调用此方法,任务只会执行一次
                jobFinished(mJobParameters,true);
            }else{
                //如果不调用此方法,任务只会执行一次
                jobFinished(mJobParameters,false);
            }

        }
    }

}

2、在AndroidManifest中注册service


      ......
      

3、调用的时候正常启动Service就可以了

你可能感兴趣的:(Android 5.0+ JobService 的使用)