Search code examples
javaandroidnotificationsalarmmanager

Having a hourly/weekly/etc... notification reminder (with AlarmManager?)


I've looked almost everywhere! I can't find any help or tutorials or examples of making a notification trigger weekly, or hourly, or monthly. I heard some things about using AlarmManager, but I can't get it working.

I haven't worked with Java much (more of an objective-c guy) but I'm having some trouble with this notification system. Basically I just want to have a button that when I toggle on will notify the user every week to re-open the app (for example). And to trigger off of course when they don't want to be notified every week to 'open the app.' Anyway, any ideas? I've figured out how to get a notification in general to come up, but I can't get it to delay, or to happen when the app isn't open.

Thanks!


Solution

  •  Calendar calendar = Calendar.getInstance();
    
        // 8 AM Each day 
        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, MyClass.class), PendingIntent.FLAG_UPDATE_CURRENT);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
    

    This will fire alarm at 8AM each day. Similarly you can set alarm for any day you like.

    TO GET NOTIFICATION :

      NotificationManager nm;
      nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);        
      CharSequence from = "VIPUL";
      CharSequence message = "Crazy About Android...";
      PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
        new Intent(), 0);
      Notification notif = new Notification(R.drawable.icon,
        "Crazy About Android...", System.currentTimeMillis());
      notif.setLatestEventInfo(context, from, message, contentIntent);
      nm.notify(1, notif);
    

    You have to write this on the activity which you calling from alarm manager. This will show you notification.

    You can also set a pending intent which will be called when user click on notification.