我的应用使用这种经典模式来安排周期性任务:
- 通过
AlarmManager
设置准确的闹钟(通过setExactAndAllowWhileIdle()
,因为即使在打瞌睡时它也必须关闭) - 通过
WakefulBroadcastReceiver.startWakefulService()
从 - 在
onHandleIntent()
中完成工作,完成后调用WakefulBroadcastReceiver.completeWakefulIntent()
。
onReceive()
启动一个 IntentService
今天我将 targetSdkVersion 更新为 26 并面对一个可怕的事实,即 WakefulBroadcastReceiver
已被弃用。
我立即去阅读 API 文档,发现了以下内容:
As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use
android.app.job.JobScheduler
to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).
这让我有点困惑,我真的不明白 AlarmManager.setExactAndAllowWhileIdle()
的目的是什么,而不能再让设备保持唤醒状态。
正如我所见,我无法设置使用 JobScheduler
运行作业的确切时间,只能设置条件(例如网络类型或充电状态),所以我不知道该怎么做。
我也想过
同时使用
AlarmManager
和JobScheduler
设置闹钟(使用
setExactAndAllowWhileIdle()
)并立即从onReceive()
开始作业(通过JobScheduler
)。由于JobScheduler
提供了一个WakeLock
,因此不需要WakefulBroadcastReceiver
。(这有意义吗?)
或
- 继续使用
WakefulBroadcastReceiver
尽管已被弃用。
我非常感谢有关此事的任何建议。
最佳答案
在 android-o 和更高版本中,您可以像这样定义一个没有 alarmmanager 的重复任务:
// schedule the start of the service "TestJobService" every 10 - 30 minutes
public static void scheduleJob(Context context) {
ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(10 * 60 * 1000); // wait at least
builder.setOverrideDeadline(30 * 60 * 1000); // maximum delay
JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
jobScheduler.schedule(builder.build());
}
关于android - 我应该如何迁移我的应用程序以使用 JobScheduler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46301253/