Search code examples
androidservicebroadcastreceiveralarmmanagerbroadcast

android service broadcast (a reminding function)


I want to have a reminding function(by set reminding time) in my app ,using notification. And I get to know that there may used service, broadcast and alarmmanger,

How can I complete this function ?

I think there are two ways:

  1. use the service ,and the notification is in service
  2. use the service to send broadcast,and the notification is in broadcastReceiver

the first question:

  1. which way is right or better?
  2. how to use that alarmmanager ? is that like the Timer class in java?

Solution

  • Simplest and most efficient way would be to use AlarmManager for something like reminders. You will need to make a BroadCastReceiver that receives your alarm. Your receiver can make the notification, since the onReceive() method of the receiver also takes in a Context parameter. To make the Alarm, you will have to get an instance of the AlarmManager Class, make a PendingIntent with what you need, then actually set the Alarm.

    Sample Code for setting an Alarm

    Intent intent = new Intent (this, AlarmBroadcastReceiver.class);
    PendingIntent pendIntent = PendingIntent.getBroadcast(this, id,  intent, //makes a new intent
    PendingIntent.FLAG_UPDATE_CURRENT); //only updates PendingIntent, does not recreate
    AlarmManager alarmManager = (AlarmManager) getSystemService (Context.ALARM_SERVICE);
    alarmManager.cancel(pendIntent); //used to cancel if previously active
    alarmManager.set(AlarmManager.RTC_WAKEUP, timeToExec, //sets the alarm to exectute once
                 pendIntent);