Unable to Cancel the Alarm through broadcast Receiver - android

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.

Related

Scheduling multiple future notifications

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

Dialy Alarm code Explanation

I am new to android , I want to make alarm that notify me dialy at 11am .I have found some code on net,But dont know some part of it. Below is code
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis()); does
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*1000, pendingIntent);
Toast.makeText(AndroidAlarmService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}});
can any one explain me what this two line does
calendar.setTimeInMillis(System.currentTimeMillis()); does
calendar.add(Calendar.SECOND, 10);
And also help me how can i set alarm that will notify me on the same time for example at 11am
Call this function where you need:
private void setDailyNotification(int ID, int hh, int mm, int ss) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(Dashboard.this, MyDailyReceiver.class);
alarmIntent.putExtra("ID", ID);
Log.d("setDailyNotification", "ID:" + ID);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
Dashboard.this, ID, alarmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mEverydayPendingIntent = pendingIntent;
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
// check whether the time is earlier than current time. If so, set it to
// tomorrow. Otherwise, all alarms for earlier time will fire
if (calendar.before(now)) {
calendar.add(Calendar.DATE, 1);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
mEverydayPendingIntent);
Log.d("setRepeated", "ID:" + ID);
}
Broadcast receiver:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context);
mBuilder.setContentTitle("Daily Summery");
mBuilder.setContentText("Today's Transaction");
mBuilder.setSmallIcon(R.drawable.app_icon);
Log.d("tag1234", "In if" + daily_Reminder);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
mBuilder.setStyle(inboxStyle);
mNotificationMa = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationMa.notify(11, mBuilder.build());
call function like this:
setDailyNotification(11, 11,00, 00);
System.currentTimeMillis()- gets the current time from the device.
calendar.setTimeInMillis()- sets the current time.
calendar.add(Calendar.SECOND, 10) - adds ten seconds to the current time.
In total, you are fetching the current time of the device and adding ten seconds in it.
You can try this Worked for me
int interval = 1000 * 60 * 1;
// 1 for minutes ,you can pass 60*24
//And set alarm manager like this
Intent alarmIntent = new Intent(AlaramManagerActivity.this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(AlaramManagerActivity.this, RQS_1, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),interval, pendingIntent);
Intent myIntent = new Intent(activity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar firingCal= Calendar.getInstance();
Calendar currentCal = Calendar.getInstance();
firingCal.set(Calendar.HOUR,11); // At the hour you wanna fire
firingCal.set(Calendar.MINUTE, 0); // Particular minute
firingCal.set(Calendar.SECOND, 0); // particular second
long intendedTime = firingCal.getTimeInMillis();
long currentTime = currentCal.getTimeInMillis();
if(intendedTime >= currentTime){
// you can add buffer time too here to ignore some small differences in milliseconds
// set from today
alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
}
else{
// set from next day
// you might consider using calendar.add() for adding one day to the current day
firingCal.add(Calendar.DAY_OF_MONTH, 1);
intendedTime = firingCal.getTimeInMillis();
alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);}

Passing int to BroadcastReceiver class using alarm manager

i am trying to pass two integers through the alarmmanger but whenever i pass them the toast replies null . i can't understand where the problem is .
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
intent.putExtra("passedHour", cal.get(Calendar.HOUR_OF_DAY));
intent.putExtra("passedMin", cal.get(Calendar.MINUTE));
PendingIntent alarmIntent = PendingIntent.getBroadcast(
MainActivity.this, 0, intent, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
alarmIntent);
This is the onreceive in alaramreceiver class
Toast.makeText(context, "Alarm!! " + intent.getStringExtra("passedHour") + ":" + intent.getStringExtra("passedMin"), Toast.LENGTH_LONG).show();
cal.get() method return int so intent is sending value as int
You need to use intent.getIntExtra method in order to get int
So in the onReceive use
Toast.makeText(context, "Alarm!! " + intent.getIntExtra("passedHour") + ":" + intent.getIntExtra("passedMin"), Toast.LENGTH_LONG).show();

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

Android AlarmManager to Trigger After One Hour

I am trying to do something really simple! I have a sessionTimeout variable which have the value 3600000 milliseconds which means 60 minutes/1 hour. I need to set the alarm after 60 minutes. I am using the following code but calendar.getTimeInMillis gives me a very high value. If I just pass 3600000 in the alarmManager it still does not work and trigger the alarm receiver instantly.
private void setupSessionTimeoutAlarm()
{
Calendar calendar = Calendar.getInstance();
calendar.add(calendar.MILLISECOND,(int) sessionTimeout);
long timeInMilliSeconds = calendar.getTimeInMillis() + sessionTimeout;
// schedule the alarm
Intent myIntent = new Intent(Gateway.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(Gateway.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,timeInMilliSeconds,pendingIntent);
}
Calendar calendar = Calendar.getInstance();
Date date = new Date();
date.setTime(System.currentTimeMillis() + (60 * 60 * 1000));
calendar.setTime(date);
Log.i(TAG, "start: " + calendar.getTime().getMinutes());
Log.i(TAG, "start: " + calendar.getTime().getHours());
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, A3LocationUpdateReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, Configuration.LocationUpdateEveryHoursRequest, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR,
pendingIntent);

Categories

Resources