I am looking for a way to create a preference
in Settings
to send a notification at a specific time of the day (set by user in settings) in an Android app. I have looked at different threads like this, however this is not working in Android Oreo.
Can someone help me with this or point me to a tutorial?
There are tons of examples of how to do this on StackOverflow, but unfortunately none of them work anymore because Google changed how the AlarmManager works.
The only AlarmManager option that allows a developer to wakeup a device at a specific time is AlarmManager.setAlarmClock.
Using setAlarmClock
In addition to the alarm, you can set an intent that will enable you to launch your app when the alarm is clicked.
The device can also be awoken at a specific time using a high priority FCM, Firebase Cloud Message.
But in summary, there is no other option: 'setExact' and associated methods no longer work as the name advertises.
After looking at different posts and some research on
AlarmManager
implementation, this is what worked for me.The base for this is this post and Schedule repeating Alarms Android Documentation.
This is my current implementation:
I have a
SwitchPreference
and aTimePicker
implementation isSettings
SwitchPreference to ask if user wants to enable Repeating Daily Notifications.
TimePicker to set the Notification time.
In
MainActivity
'sOnCreate
method or wherever you are reading theSharedPreferences
do this:Next add
AlarmReceiver
class that implementsBroadcastReceiver
like this:The system will turn off the
AlarmManager
if Device is powered off or reboots, so restart it again onBOOT COMPLETE
add this class:And Finally do not forget to add these permissions to
AndroidManidest
:and register your receivers in
AndroidManifest
The
Notification
should be set by this at a specific time of the day specified byTimePicker
and if user enabled theSwitchPreference
.