Я использую workmanager для отправки уведомлений каждые 15 минут.Это мой код:
class UpdateWorker(context : Context, params : WorkerParameters)
: Worker(context, params) {
override fun doWork(): Result {
// Do the work here--in this case, compress the stored images.
// In this example no parameters are passed; the task is
// assumed to be "compress the whole library."
sendNotification("WorkManager", "EL work manager funciona.")
// Indicate success or failure with your return value:
return Result.success()
// (Returning Result.retry() tells WorkManager to try this task again
// later; Result.failure() says not to try again.)
}
fun sendNotification(title: String, message: String) {
Log.e("Work manager", "Sync");
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//If on Oreo then notification required a notification channel.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val channel = NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(applicationContext, "default")
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
notificationManager.notify(1, notification.build())
}
}
В MainActivity:
//work manager
val myConstraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
// Many other constraints are available, see the
// Constraints.Builder reference
.build()
val updateWork = PeriodicWorkRequest.Builder(UpdateWorker::class.java, 15, TimeUnit.MINUTES)
.setConstraints(myConstraints)
.build()
WorkManager.getInstance().enqueue(updateWork!!)
//end workmanager
Что происходит, я не понимаю, почему, если я укажу, что уведомление отправляется каждые 15 минут, ононе показано в то время.Посмотрите журнал времени, в которое он показан:
02-07 16:30:11.371 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:33:10.831 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.611 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.631 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.651 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.661 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.671 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.681 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.701 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.711 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.731 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.751 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:40:50.041 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:43:55.861 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:45:11.441 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync