Если каждый час, то WorkManager периодическая работа будет хорошим выбором
fun createConstraints() = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED) // if connected to WIFI
// other values(NOT_REQUIRED, CONNECTED, NOT_ROAMING, METERED)
.setRequiresBatteryNotLow(true) // if the battery is not low
.setRequiresStorageNotLow(true) // if the storage is not low
.build()
fun createWorkRequest(data: Data) = PeriodicWorkRequestBuilder<LocationWorker>(12, TimeUnit.HOURS) // setting period to 12 hours
// set input data for the work
.setInputData(data)
.setConstraints(createConstraints())
// setting a backoff on case the work needs to retry
.setBackoffCriteria(BackoffPolicy.LINEAR, PeriodicWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
.build()
fun startWork() {
// set the input data, it is like a Bundle
val work = createWorkRequest(Data.EMPTY)
/* enqueue a work, ExistingPeriodicWorkPolicy.KEEP means that if this work already existits, it will be kept
if the value is ExistingPeriodicWorkPolicy.REPLACE, then the work will be replaced */
WorkManager.getInstance().enqueueUniquePeriodicWork("Smart work", ExistingPeriodicWorkPolicy.KEEP, work)
// Observe the result od the work
WorkManager.getInstance().getWorkInfoByIdLiveData(work.id)
.observe(lifecycleOwner, Observer { workInfo ->
if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
// FINISHED SUCCESSFULLY!
}
})
}
Вот полный пример использования WorkManager
в зависимости от ваших потребностей.
менеджер работ имеет doWork()
метод, при котором вы можете создавать уведомления при необходимости
Вот пример того, как создать уведомление
val intent = Intent(this, AlertDetails::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true)
Обязательно создайте канал уведомлений во время использования уведомления.
В здесь подробно объясняется, как создать уведомление.