在Android 12上,JobScheduler将无法在设备锁定或启动时启动JobService的作业。这是由于在此类型的情况下JobScheduler无法访问应用程序的数据目录。为了解决这个问题,你可以通过使用JobScheduler的新API - schedule(boolean allowWhileIdle, JobInfo job),并将allowWhileIdle参数设置为true来允许在设备锁定/直接启动时启动JobService的作业。
示例代码如下:
JobInfo.Builder builder = new JobInfo.Builder(jobId, component);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_EXPONENTIAL);
builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
builder.setImportantWhileForeground(true);
builder.setPrefetch(true);
builder.setImportantWhileForeground(true);
builder.setImportantWhileForeground(true);
builder.setPrefetch(true);
builder.setImportantWhileForeground(true);
builder.setPrefetch(true);
builder.setImportantWhileForeground(true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setRequiresBatteryNotLow(true);
builder.setRequiresCharging(false);
builder.setRequiresDeviceIdle(false);
builder.setRequiresStorageNotLow(true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setEstimatedNetworkBytes(JobInfo.SIZE_UNKNOWN, JobInfo.SIZE_UNKNOWN);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setImportantWhileForeground(true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
builder.setTriggerContentMaxDelay(JobInfo.DEFAULT_TRIGGER_UPDATE_DELAY);
builder.setTriggerContentUpdateDelay(JobInfo.DEFAULT_TRIGGER_UPDATE_DELAY);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
builder.setPrefetch(true);
builder.setPrefetch(true);
builder.setPrefetch(true);
builder.setPrefetch(true);
}
builder.setPersisted(true);
if (Build.VERSION.SDK_INT <