Search code examples
androidandroid-notificationsandroid-alarms

How to get an alarm to trigger a notification


I need to set a repeating alarm that will once fired, launch a notification.

Steps:

  1. I have an interface that takes some date details (Just had a thought, maybe I should be launching an intent to display the "set alarm" feature). The product of the details is a date time string that needs to be fed into an alarm method.
  2. When setting an alarm I need to create a reference to it so it can be deleted by the user. (Or maybe not, what is best practice? Maybe users can only delete an alarm from the "alarm" section)
  3. When the alarm goes off a notification will be created.

I'm uncertain of how the alarm system works. The alarm probaly should be silent, maybe with vibration. Is that straight forward to setup?

Do I need a service or will a broadcast reciever do the job?

Basically I just need a few pointers. Am I thinking about this correctly? Is there a tutorial out there (I haven't found anything). Thanks in advance.


Solution

  • Here is a walkthrough on how I use an AlarmService in my app.

    1. Set up an AlarmManager to fire in x minutes.

    2. In response to the alarm, start a service.

    3. Create your notification and have your service set itself up with a new Alarm to fire again in another x minutes.

    4. The service shuts itself down.

    1.

        Intent alarmIntent = new Intent(this, MyAlarm.class);
        long scTime = 60* 10000;// 10 minutes
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + scTime, pendingIntent);
    

    2.

        public class MyAlarm extends BroadcastReceiver
        {
    
           @Override
           public void onReceive(Context context, Intent intent) {
              Log.d("Alarm Recieved!", "YAAAY");
              Intent i = new Intent(context, InviteService.class);
              context.startService(i);
           }
        }
    

    3.

          public class InviteService extends IntentService
     {
    
      /** 
       * A constructor is required, and must call the super IntentService(String)
       * constructor with a name for the worker thread.
       */
    
      public InviteService() {
          super("InviteService");
      }
    
      /**
       * The IntentService calls this method from the default worker thread with
       * the intent that started the service. When this method returns, IntentService
       * stops the service, as appropriate.
       */
    
      @Override
      protected void onHandleIntent(Intent intent) {
    
                      String ns = Context.NOTIFICATION_SERVICE;
                      NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    
                      int icon = R.drawable.logo;
                      CharSequence tickerText = "New Invite!";
                      long when = System.currentTimeMillis();
    
                      Notification notification = new Notification(icon, tickerText, when);
                      notification.flags |= Notification.FLAG_AUTO_CANCEL;
                      notification.defaults |= Notification.DEFAULT_VIBRATE;
    
                      Context context = getApplicationContext();
                      CharSequence contentTitle = "Title";
                      CharSequence contentText = "Text";
                      Intent notificationIntent = new Intent(this, Destination.class);
                      Bundle partyBundle = new Bundle();                    
    
                      PendingIntent contentIntent = PendingIntent.getActivity(this, SOME_ID, notificationIntent, 0);
    
                      notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    
                      int NOTIFICATION_ID = SOME_ID;
    
                      Log.d("NOTIFICATION_ID", "" + NOTIFICATION_ID);
                      mNotificationManager.notify(NOTIFICATION_ID, notification);
    

    4.(In the Same Class)

          Intent alarmIntent = new Intent(this, MyAlarm.class);
          long scTime = 60*1000;//mins
          PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
          AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
          alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + scTime, pendingIntent);
    
          stopService(intent);
          }
        }
    

    Hope this helps!

    EDIT

    Why use a Service?

    It's not wise to do much processing in the BroadcastReceiver. Although you can do some processing in the BroadcastReciever, it is safer to do this in a Service, you can find some information in this StackOverflow question BroadcastReceiver vs Service