Search code examples
androidbroadcastreceiveralarmmanager

android - how to push notification (reminder) on a specific time?


I checked almost all questions in stack overflow and also in google documentation and still couldn't understand what to use exactly for my cases.

What i want is, user will select reminder date in the app and in that time app will send a notification even app is closed or phone restarted between remind set time and remind time.

So what do i need to use? Which classes do i need? Broadcast Receiver, AlarmManager these two is enough or what? a sample of code 20-30 lines would be nice =)


Solution

  • You will need both a few things.

    Setup: You need to set your app to listen for the phone starting by registering for this intent in your manifest.

    Basically you when your user selects the time, you will need to:

    1. Save that time in a file/db/shared prefs.
    2. Set the alarm manager to wake up your app at the right time
    3. When the alarm manager sends you a broadcast, start a service to do the necessary work (broadcast receivers have to complete their work in a short amount of time, so it's better to start a service)
    4. In your service, remove the time from your file/db/shared prefs

    If your app ever gets the broadcast that the phone was rebooted, then all of your alarms are lost. You need to reset them using the times you saved in the file/db/shared prefs.