Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AlarmManager Push notifications

I am using this notifications code:

package com.example.mega;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;


public class TimeAlarm extends BroadcastReceiver {

     NotificationManager nm;

     @Override
     public void onReceive(Context context, Intent intent) {
         nm = (NotificationManager) context
             .getSystemService(Context.NOTIFICATION_SERVICE);
         CharSequence from = "Tech";
         CharSequence message = "Check out our NEW COLLECTION !!";
         PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
             new Intent(), 0);
         Notification notif = new Notification(R.drawable.icon,
             "Check out our NEW COLLECTION !!" , System.currentTimeMillis());
         notif.setLatestEventInfo(context, from, message, contentIntent);
         nm.notify(1, notif);
    }
}

As you see I haven't yet added AlarmManager since I have no experience using it ,I am new to android.What should I add to the code to have show the notification every 24 hours ??

like image 657
user2558256 Avatar asked Oct 04 '22 08:10

user2558256


1 Answers

Calendar calendar = Calendar.getInstance();
// 8.00 (8 AM) 
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

PendingIntent pi = PendingIntent.getService(context, 0 , new Intent(context, Your_Class.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                            AlarmManager.INTERVAL_DAY, pi);

This sets an alarm everyday at 8.00 AM

Or you can use https://github.com/commonsguy/cwac-wakeful. Take a look at the documentation on the link.

Take a look at this: Fire notification at every 24 hours and at exact time of 8 AM

And this: http://blog.blundellapps.com/notification-for-a-user-chosen-time/

like image 96
Stefano Munarini Avatar answered Oct 12 '22 12:10

Stefano Munarini