Search code examples
androidbroadcastreceiveralarmmanagerandroid-pendingintent

Do i need to use broadcast with alarm manager?


i'm creating an alarm application, and this is the method to run the alarm :

public void startAlarm(int minuteToStart)
{

    Toast.makeText(context, "Alarm Start in " + formatTime(minuteToStart), Toast.LENGTH_SHORT).show();
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, minuteToStart);    
    Intent intent = new Intent(context, AlarmActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, idPendingIntent, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}

And it run this activity after given specific time:

public class AlarmActivity extends Activity {
......
}

It works, but i see people are using BroadcastReceiver, am i doing it wrong? should i use BroadcastReceiver too? I've been searching about BroadcastReceiver but i don't get what difference it will make with my application.

Thanks.


Solution

  • In the general case, A--C's answer would be correct.

    However, you are using RTC_WAKEUP as the alarm type. The only guarantee that we have with _WAKEUP alarms is if we use a BroadcastReceiver, then Android will ensure that the device will stay awake long enough for us to execute onReceive(). Any other type of PendingIntent -- activity or service -- has no guarantee, and it is very possible for the device to fall back asleep before the startActivity() or startService() actually occurs.