其他分享
首页 > 其他分享> > Job Scheduler未在Android N上运行

Job Scheduler未在Android N上运行

作者:互联网

Job Scheduler在Android Marshmallow和Lollipop设备上按预期工作,但它没有运行和Nexus 5x(Android N预览版).

用于安排作业的代码

        ComponentName componentName = new ComponentName(MainActivity.this, TestJobService.class.getName());
        JobInfo.Builder builder;
        builder = new JobInfo.Builder(JOB_ID, componentName);
        builder.setPeriodic(5000);
        JobInfo jobInfo;
        jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobInfo = builder.build();
        int jobId = jobScheduler.schedule(jobInfo);

服务在清单中定义为:

<service android:name=".TestJobService"
            android:permission="android.permission.BIND_JOB_SERVICE" />

在Android N(预览版)上是否有任何人遇到此问题?

解决方法:

在Android Nougat中,setPeriodic(long intervalMillis)方法调用使用setPeriodic (long intervalMillis, long flexMillis)来安排定期作业.

根据文件:

JobInfo.Builder setPeriodic (long intervalMillis, long flexMillis)

Specify that this job should recur with the provided interval and
flex. The job can execute at any time in a window of flex length at
the end of the period.

intervalMillis long:
Millisecond interval for which this job will repeat. A minimum value of getMinPeriodMillis() is enforced.

flexMillis long:
Millisecond flex for this job. Flex is clamped to be at least getMinFlexMillis() or 5 percent of the period, whichever is higher.

示例定期作业计划为5秒:

private static final int JOB_ID = 1001;
private static final long REFRESH_INTERVAL  = 5 * 1000; // 5 seconds

JobInfo jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
        .setPeriodic(REFRESH_INTERVAL)
        .setExtras(bundle).build();

以上代码适用于Lollipop&棉花糖但是当你在牛轧糖中运行时你会注意到以下日志:

W/JobInfo: Specified interval for 1001 is +5s0ms. Clamped to +15m0s0ms
W/JobInfo: Specified flex for 1001 is +5s0ms. Clamped to +5m0s0ms

因为我们将周期性刷新间隔设置为5秒,小于thresholdgetMinPeriodMillis(). Android Nougat强制执行getMinPeriodMillis().

作为一种解决方法,如果作业间隔小于15分钟,我将使用以下代码定期调度作业.

JobInfo jobInfo;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
      .setMinimumLatency(REFRESH_INTERVAL)
      .setExtras(bundle).build();
} else {
  jobInfo = new JobInfo.Builder(JOB_ID, serviceName)
      .setPeriodic(REFRESH_INTERVAL)
      .setExtras(bundle).build();
}

示例JobService示例:

public class SampleService extends JobService {
    @Override public boolean onStartJob(JobParameters params) {
        doSampleJob(params); 
        return true;
    }

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

    public void doSampleJob(JobParameters params) {
        // Do some heavy operation
        ...... 
        // At the end inform job manager the status of the job.
        jobFinished(params, false);
    }
}

标签:android-7-0-nougat,android,android-jobscheduler
来源: https://codeday.me/bug/20190918/1811878.html