简体   繁体   中英

Re-enable alarms (non-repeating) that were not previously notified before shutdown, on android boot

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:

  • 3 alarms only, all non-repeating. One alarm each is scheduled for Day 1, Day 2, and Day 3.
  • Information for these alarms is stored in Room database.
  • The phone is on during Day 1 and Alarm 1 fired normally (user did not open the app during day 1 so only see the notification as a popup). Note this alarm is part of an "event", and the event does not get deleted.
  • The phone is turned off entirely during Day 2.
  • The phone is turned on at beginning of Day 3. The expectation is that the Day 2 alarm will fire immediately on reboot, and then Day 3 alarm will fire at the scheduled time.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM