I am new to Android notification, and I have a question regarding after device reboot, how to re-enable only those alarms that did not notify previously before shutdown. As an example:
My understanding from reading about setting up a BootReceiver / BroadcastReceiver is that once the device reboots, all notifications are cancelled, and I will need to re-enable them in the BootReceiver. How can I make sure I re-enable the Day 2 and Day 3 alarms only?
Conceptually, I'm thinking of 2 possibilities: Option 1: Whenever an alarm notification appears, without requiring to open the app, modify a flag in the database to indicate that the alarm had fired. Then inside the BootReceiver, filter active alarms from database to re-enable based on the flag. Is this possible? The database needs to be manipulated when the alarm notification pops up, without even launching the app.
Option 2: Inside the BootReceiver, filter from the database as "alarm time > last shutdown time". There seems to be a way to use Intent.ACTION_SHUTDOWN to store the last shutdown time in SharedPreferences, but I'm not sure how reliable this is, eg will the save be successful if the device shut down unexpectedly.
I'm not certain if I'm on the correct track in this use case. Any suggestions or code example would be appreciated.
I got Option 1 to work. Using Google Codelab example , pass the repository to the sendNotification function, and add codes at the end to modify database.
fun NotificationManager.sendNotification(messageBody: String, applicationContext: Context, repository: MyRepository) {
...
notify(NOTIFICATION_ID, builder.build())
val viewModelJob = Job()
val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
uiScope.launch {
withContext(Dispatchers.IO) {
repository.updateNotificationStatus(id, true)
}
Timber.i("At the time when notification appears, database's status flag will change to true")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.