Aerrow Aerrow - 4 months ago 15
Android Question

How to develop Android Alarm application

I tried to develop a sample Alarm Application. I searched Google and SC, most of their examples confused. How can I create an alarm application with the following requirements,


  1. In My Home screen i have a button, like "START ALARM", when i click the button a time picker must enable.

  2. I select the time as I wish, once I pick the time, the alarm icon will enabled on widget. (For example if we set the alarm in default mobile Alarm application, the icon will be enabled, that indicates the alarm is set).

  3. When the set time is reached (the time which is set form the TimePicker app), the alarm will beep.



These are my requirements, I finished the first two points, but I'm still struggling on setting the alarm.

Answer

Take a look at AlarmManager. And, If you want to use alarm simultaneously you must use Service class for that. And, see below sample code -

public class OnBootReceiver extends BroadcastReceiver {
  private static final int PERIOD=300000;  // 5 minutes

  @Override
  public void onReceive(Context context, Intent intent) {
    AlarmManager mgr =
      (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(context, OnAlarmReceiver.class);
    PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
      SystemClock.elapsedRealtime()+60000, PERIOD, pi);
  }

This will repeat the alarm with every 6 Mins. See Scheduling Repeating Alarms document.