Scheduling multiple future notifications - android

I am currently debugging an issue with notifications inside my application. For some context, what I'd like to do is schedule notifications that should popup whenever a rocket launch is occurring. What I was doing was, after getting a list of scheduled launches from an API, I would take the launch date (in milliseconds since Jan 1 1970) and subtract the System.currentTimeMillis() from it. I would then use the resulting time to schedule the notification in the future, represented as System.currentTimeMillis() + timeDifference. I noticed that for whatever reason, only 1 notification is ever displayed.
I've tried debugging by scheduling notifications at 2, 4, and 6 minutes in the future, however a notification is only displayed at the 6 minute mark.
Some relevant code is below:
public void scheduleNotifications(List<Launch> launches) {
for(int i = 0; i < launches.size(); i++) {
SimpleDateFormat format = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss z");
Date date = null;
try {
date = format.parse(launches.get(i).getWindowstart());
} catch (ParseException e) {
e.printStackTrace();
}
long timeBetween = date.getTime() - System.currentTimeMillis();
Integer id = Long.valueOf(date.getTime()).intValue();
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, id);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, getNotification(launches.get(i).getRocket().getName(), launches.get(i).getLocation().getPads().get(0).getName()));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Debug. Schedule at 2, 4, 6 minutes.
if (i == 0) {
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 120000, pendingIntent);
}
if (i == 1) {
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 240000, pendingIntent);
}
if (i == 2) {
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 360000, pendingIntent);
}
}
}
private Notification getNotification(String rocketName, String padName) {
Notification.Builder builder = new Notification.Builder(this);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
builder.setContentIntent(pendingIntent);
builder.setContentTitle("Upcoming Launch");
builder.setContentText("A launch of a " + rocketName + " is about to occur at " + padName + ". Click for more info.");
builder.setSmallIcon(R.drawable.rocket_icon);
return builder.build();
}
Broadcast Receiver:
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
I'd like to know why only a single notification is ever presented, as well as what I need to add to achieve the previously stated goal.

When you set an alarm using AlarmManager, it automatically cancels any existing alarm that has a matching PendingIntent. Since all your PendingIntents contain the same components, every time you set an alarm, the previously set ones are automatically cancelled.
If you want to set multiple alarms, you must make sure that each of the PendingIntents is unique. You can do this in one of the following ways:
Use a different requestCode (second parameter to PendingIntent.getBroadcast()) for each PendingIntent
Use a different ACTION in the Intent you pass to PendingIntent.getBroadcast() for each PendingIntent

Related

AlarmManager shifts time by 12 hours

I'm trying to create periodical notifications.
So, I created a function to reschedule new notification time:
private void rescheduleNotification(Context context) {
long nextNotifTime = System.currentTimeMillis();
// Schedule next notification in 15 minutes
nextNotifTime += 15 * 60 * 1000;
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(nextNotifTime);
// It's an old version with the same result
//calendar.add(Calendar.MINUTE, 15);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss", Locale.ENGLISH);
this.logEvent(" Next notification time is: " + sdf.format(calendar.getTimeInMillis()));
Intent intent = new Intent(context, WordsBcReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager manager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 23) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextNotifTime, pendingIntent);
} else {
manager.set(AlarmManager.RTC_WAKEUP, nextNotifTime, pendingIntent);
}
this.logEvent(" Set next notification time: " + sdf.format(nextNotifTime));
}
Sometimes it runs correctly, but sometimes notification time shifts by exactly 12 hours.
I added special function to log all time manipulations, so the log contains:
29/12/17 11:30:36: Next notification time is: 29/12/17 12:00:36
29/12/17 11:30:36: Set next notification time: 29/12/17 12:00:36
seems OK, but adb shell dumpsys alarm says:
type=0 whenElapsed=+11h34m13s906ms when=2017-12-30 00:00:36
I tried to use Calendar (I to exclude some periods later), but result was the same.
Can't find the problem...

Unable to Cancel the Alarm through broadcast Receiver

I'm trying to cancel the repeating notifications on a particular date, so I'm setting it in a broadcast receiver which is fired on that particular time cancelling the repeating notifications through that unique id. but it is not cancelling the notifications. I have tried two techniques both are mentioned below.
mainActivity's code where I'm setting the Alarm.
Log.v("setting range alarm","key range id = " + keyIds[j] + "time = " + RangeTimes[j]);
// Setting the alarm for repeating notifications, with different broadcast Receiver (alertIntent).
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, RangeTimes[j], AlarmManager.INTERVAL_DAY,
PendingIntent.getBroadcast(this, keyIds[j], alertIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // for exact repeating THIS
Log.v("setting range alarm","key range id = " + keyIds[j] + "Cancel time = " + CancelRangeTimes[j]);
// Setting the alarm for cancellin the repeating notifications, with different broadcast Receiver(cancelIntent).
cancelIntent.putExtra("CancelID", keyIds[j]);
cancelIntent.putExtra("key", pendingIntent);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC_WAKEUP, CancelRangeTimes[j],
PendingIntent.getBroadcast(this, keyIds[j], cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // for exact repeating THIS
here is the cancelling broadcast reciver which is not working even though it is getting called on the right time.
#Override
public void onReceive(Context context, Intent intent) {
String pleaseText = intent.getStringExtra("text");
// Methid # 1 ( By getting the Alarm id through intent and trying to cancel on the same id
/*
int cancelReqCode = intent.getIntExtra("CancelID", 0);
Log.v("setting the cancel", "inside broadCast reciver " + cancelReqCode);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, cancelReqCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Log.v("setting the cancel", "inside broadCast reciver " + pendingIntent);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
*/
// Methid # 2
Log.i("okk", "please text insode cancel" + pleaseText);
PendingIntent pendingIntent = intent.getParcelableExtra("key");
Log.v("setting the cancel","inside broadCast reciver " + pendingIntent );
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
}
// below is the mainActvity's code where i'm setting alaram managers, alertIntent, CancelIntent and Pending Intents. I have omitted the code where it is getting the array values and setting them because it was useless here, but every date value is correct. this setAlarm() is getting called in the onCreate method.
public class MainActivity extends ActionBarActivity implements AsyncResponse, View.OnClickListener {
AlarmManager alarmManager;
PendingIntent pendingIntent;
public void setAlarm1() {
long[] RangeTimes = new long[C.getCount()];
long[] CancelRangeTimes = new long[C.getCount()];
String rangeCheck = "false" ;
int[] KeyRangeIds = new int[C.getCount()];
Intent alertIntent = new Intent(this, AlertReceiver.class);
Intent cancelIntent = new Intent(this, CancelAlarmBroadcastReceiver.class);
alertIntent.putExtra("strings", DealTimes);
cancelIntent.putExtra("strings", DealTimes);
// ------------------------- SETTING ALARM --------------------------------
for (int i = 0; i < UserFoodType.length; i++) {
for (int j = 0; j < C.getCount(); j++) {
RangeTimes[j] = calendar.getTimeInMillis();
CancelRangeTimes[j] = calendar1.getTimeInMillis();
}
if(FoodType[j].equals(UserFoodType[i]))
{
for (int k = 0; k < UserDealZone.length; k++) {
if(DealZone[j].equals(UserDealZone[k]))
{
Log.v("setting range alarm","key range id = " + keyIds[j] + "time = " + RangeTimes[j]);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, RangeTimes[j], AlarmManager.INTERVAL_DAY,
PendingIntent.getBroadcast(this, keyIds[j], alertIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // for exact repeating THIS
Log.v("setting range alarm","key range id = " + keyIds[j] + "Cancel time = " + CancelRangeTimes[j]);
// alertIntent.putExtra("cancelID", keyIds[j]);
cancelIntent.putExtra("CancelID", keyIds[j]);
cancelIntent.putExtra("key", pendingIntent);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC_WAKEUP, CancelRangeTimes[j],
PendingIntent.getBroadcast(this, keyIds[j], cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // for exact repeating THIS
}
}
}
You are putting an extra in cancelIntent, like this:
cancelIntent.putExtra("key", pendingIntent);
however, pendingIntent is never initialized, so it will be null.
When CancelAlarmBroadcastReceiver.onReceive() is called, this code:
PendingIntent pendingIntent = intent.getParcelableExtra("key");
is probably returning null. You are logging that, you should be able to check.
In any case, if pendingIntent is null, calling AlarmManager.cancel() won't do anything.

Repeating alarm wont work in Android

User can set their own repeat interval, for example he/she selected 5 minutes to be reminded of the new goal she set. The reminder will start on the goal's start date which is also set by the user.
No problem with setting goal, and setting the repeat interval. The problem is it wont work.
What i would like to happen: This is an example
Goal 1 starts tomorrow. User will get reminder of Goal 1 in every 1 hour tomorrow.
Here's my code:
public void setReminder(){
List<Goals> oneGoal = dbhandler.getLatestGoal(goal_id);
for (final Goals goals : oneGoal) {
if (repeat.isChecked()) {
long futureInMillis = 0;
dbhandler.updateReminders("true",choiceNumber,choiceRepeat,goal_id);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.DATE,Integer.parseInt(goals.getSDay())); //1-31
cal.set(Calendar.MONTH,Integer.parseInt(goals.getSMonth())-1); //first month is 0!!! January is zero!!!
cal.set(Calendar.YEAR, Integer.parseInt(goals.getSYear()));//year...
//assigned a unique id to notifications
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
//Create a new PendingIntent and add it to the AlarmManager
Intent intent3 = new Intent(this, TimeAlarm.class);
intent3.putExtra("goalid", Integer.toString(goal_id));
PendingIntent pendingIntent = PendingIntent.getActivity(this,
goals.getGoalId(), intent3, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager) getSystemService(Activity.ALARM_SERVICE);
if (choiceRepeat.equalsIgnoreCase("Seconds")) {
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * choiceNumber,
pendingIntent);
} else if (choiceRepeat.equalsIgnoreCase("Minutes")) {
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * 60 * choiceNumber,
pendingIntent);
} else if (choiceRepeat.equalsIgnoreCase("Hours")) {
am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1000 * 60 * 60 * choiceNumber,
pendingIntent);
}
MessageTo.message(SetReminderActivity.this, "You will be reminded every "+choiceNumber+" "+choiceRepeat+" for the new goal.");
//am.cancel(pendingIntent);
}else{
MessageTo.message(SetReminderActivity.this, "You've chosen not to set reminder for the new goal.");
}
}
}
TimeAlarm.java // for the notifications
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
MyDBAdapter dbhandler;
#Override
public void onReceive(Context context, Intent intent) {
int goal_id = Integer.parseInt(intent.getStringExtra("goalid"));
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
//assigned a unique id to notifications
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
List<Goals> oneGoal = dbhandler.getLatestGoal(goal_id);
for (final Goals goals : oneGoal) {
Notification mNotification = new Notification.Builder(context)
.setContentTitle("A Reminder from GSO")
.setContentText(goals.getGoalName())
.setSubText(goals.getStartDate() + " - " + goals.getEndDate())
.setSmallIcon(R.drawable.gsoicon)
.setContentIntent(contentIntent)
.setSound(soundUri)
.build();
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// If you want to hide the notification after it was selected, do the code below
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(m, mNotification);
}
}
}
in Android Manifest:
<receiver android:name=".TimeAlarm" />
I can't tell what wrong with my code. Pls. help.
You are only setting the alarm using AlarmManager's set() method. You should use setRepeating() method for repeating the alarm events.
So, your below line
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
should be replaced with
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
You can also refer this Example : Create Repeating Alarm .
Example to repeat event on every two minutes
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),2*60*60,pendingIntent);
You have to declare the receiver in your AndroidManifest.xml
<receiver android:name="TimeAlarm" >
See: http://developer.android.com/guide/topics/manifest/receiver-element.html

Notification Message Instantly Fired - Android

I'm making an app that stores medicines data in an SQLite database in order to send to the user notifications when it's time to take them.
I already created the BroadcastReceiver class and managed the notification Intent.
The Calendar.set() function is called when I add the time (hh:mm:ss) in the database but the problem is that every time I set the time in the TimePicker dialog, the notification is sent instantly, at regardless from time.
Here is the setAlarm function from the activity where I store the time and the other stuff:
public void setAlarm()
{
String mName = NameFld.getText().toString();
String mFormat = FormatSpn.getSelectedItem().toString();
Calendar calendar = Calendar.getInstance();
char[] sTime = TimeBtn.getText().toString().toCharArray();
if(sTime[0] == '0')
{
calendar.set(Calendar.HOUR_OF_DAY, sTime[1]);
}
else
{
String tmp = "";
tmp += sTime[0];
tmp += sTime[1];
int hour = Integer.parseInt(tmp);
calendar.set(Calendar.HOUR_OF_DAY, hour);
}
if(sTime[3] == '0')
{
calendar.set(Calendar.MINUTE, sTime[4]);
}
else
{
String tmp = "";
tmp += sTime[3];
tmp += sTime[4];
int minute = Integer.parseInt(tmp);
calendar.set(Calendar.MINUTE, minute);
}
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("mName", mName);
intent.putExtra("mFormat", mFormat);
sendBroadcast(intent);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
aManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
The two lines of code below:
String mName = NameFld.getText().toString();
String mFormat = FormatSpn.getSelectedItem().toString();
Just takes data from the EditText fields then put in an Intent to manage them in the notification building.
In order to set the time to the Calendar variable, I take the text from the TimeBtn button that consists in the time string itself. I just set it when I pick the time from the TimePicker dialog.
Then I cast it in a char array in order to split hour and minute values and I put them in the calendar.set() function, distinguishing if the value starts with 0 to avoid an octal conversion when I cast them to int.
Once the time has been set, the AlarmReceiver class (extends BroadcastReceiver) does the following:
#Override
public void onReceive(Context context, Intent intent) {
String mName = intent.getStringExtra("mName");
String mFormat = intent.getStringExtra("mFormat");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);
builder.setTicker("It's pill time!");
builder.setContentTitle(mName);
builder.setContentText(mFormat);
builder.setSmallIcon(R.drawable.ic_launcher);
Notification notification = builder.build();
NotificationManager nManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
nManager.notify(0, notification);
}
There aren't compilation errors, I just can't spot the issue.
Thanks in advance for any help!
Try replacing
aManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
with
aManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+calendar.getTimeInMillis(), pIntent);

Show multiple notifications per day in android using Alarm manager

I want to show 2 notifications per day in my application in 2 specific time, until now i'm just able to show one notification.
This is my code, how can i show multiple notification.
one at 7 AM , and the other at 6 PM for example?
Intent myIntent = new Intent(Calender.this, MyAlarmService.class);
int id = (int) System.currentTimeMillis();
pendingIntent = PendingIntent.getService(Calender.this, id,
myIntent, Notification.FLAG_ONLY_ALERT_ONCE);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar timeToSet = Calendar.getInstance();
timeToSet.set(Calendar.HOUR_OF_DAY, hour);
alarmManager.set(AlarmManager.RTC_WAKEUP,
timeToSet.getTimeInMillis(), pendingIntent);
and i called this in MyAlarmService in the onStart method
final Calendar c = Calendar.getInstance();
Notification note = new Notification(R.drawable.icon,
getString(R.string.app_name), System.currentTimeMillis());
Intent intent = new Intent(this, Calender.class);
PendingIntent i = PendingIntent.getActivity(this, 0, intent,
Notification.FLAG_ONGOING_EVENT);
note.setLatestEventInfo(this, getString(R.string.app_name),
"Some String", i);
note.flags |= Notification.FLAG_AUTO_CANCEL;
NOTIFY_ME_ID = System.currentTimeMillis();
mgr.notify((int) NOTIFY_ME_ID, note);
You should set different keys for different notifications. If you use one key for several notifications it will rewrite the same one.

Categories

Resources