Android reminder notifications

Tram Ho

Prologue

As of API 19, all AlarmManager iterators are incorrect. This creates many difficulties for programmers. After a while of researching, I decided to use setExact to send notifications once. In the notification function, I will use the data in the room database to set it up for the next notification.

1. Granting permissions

  • We need the SCHEDULE_EXACT_ALARM permission for the AlarmManager.setExact function to work.
  • SCHEDULE_EXACT_ALARM will be automatically granted for API <= 31
  • For API > 31 we need to check and ask for permission if not allowed.
  • Check permissions:

Request permission:

2. Create ReminderBroadcastReceiver

  • We use BroadcastReceiver to receive event and display Notification to user
  • Use room to test and execute setExact Alarm for next time

  • If the reminder in the room has not been deleted, then set it for the next time

Add to manifest file

3. Create a class to manage adding and canceling Notifications

  • Here I use requestCode in pendingIntent equal to the Id of the notification in the room for the convenience of canceling Notification

4. Call the function that displays Notification

  • Add Notification in Room Database.
  • Use the returned Id to set the notificationId to facilitate editing and canceling Notification

  • Trigger

  1. Reboot handling
  • After the phone is rebooted. The functions in the AlarmManager will be reset. So we need to catch reboot event and reset reminder to show Notification. Here I will use broadcast receiver

  • Declare in manifest

Share the news now

Source : Viblo