我写了一些关于Ragesh Ramesh提到的WorkManager的代码片段。
它适用于Pixel 6中的您的使用情况。
- 应用程序已关闭(如已杀死)
- 手机已重启,但尚未重新启动应用程序。
根据文档,WorkManager应该满足您的要求
计划的工作存储在内部管理的SQLite数据库中,WorkManager负责确保此工作持久存在,并在设备重新启动时重新安排
其他注意事项,WorkManager的限制
因此,即使对WorkRequest设置的所有约束都得到满足,您的工作仍可能会有一些额外的延迟。
如果您仍然有问题,请查找Google实验室(WorkManager),我的意见可能与OEM问题相关。
class OneTimeScheduleWorker(
val context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams) {
override fun doWork(): Result {
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.android_cupcake)
.setContentTitle("Scheduled notification")
.setContentText("Hello from one-time worker!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(context)) {
notify(Random.nextInt(), builder.build())
}
return Result.retry()
}
}
fun schedulePeriodicNotifications() {
val periodicWork = PeriodicWorkRequestBuilder<OneTimeScheduleWorker>(
15, TimeUnit.MINUTES
).addTag("WORK_TAG").build()
WorkManager.getInstance(this)
.enqueueUniquePeriodicWork(
"WORK_NAME",
ExistingPeriodicWorkPolicy.KEEP,
periodicWork
)
}
如果需要,可以将以下代码添加为build-notification
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.appwidget_text)
val descriptionText = getString(R.string.looper_event)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}