Cancel an AlarmManager pendingIntent in another pendingintent - android

I want cancel AlarmManager which define a service,in this service might start a new AlarmManger or cancel alarm that defined before.And I know the params pendingintent in alarmManager.cancel(PendingIntent),must be the same.compare with filterEquals(Intent other)
but It still not work.cancel failed.
here is my code
public class GetRoundStroe {
private Store[] stores;
private Context mContext;
public GetRoundStroe(Context mContext) {
this.mContext = mContext;
}
public Store[] getStores() {
if (ComCommand.haveInternet(mContext)) {
start_am_normal();
} else {
start_am_silence();
}
return stores;
}
public Store[] start_am_silence() {
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
if (AlarmHolder.mAlarmNormal != null) {
am.cancel(AlarmHolder.mAlarmNormal);
}
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, TestSwitch.getInstance().getSilence_time(), AlarmHolder.mAlarmSilence);
return null;
}
public Store[] start_am_normal() {
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
if (AlarmHolder.mAlarmSilence != null) {
MyLog.e(GetRoundStroe.class,"AlarmHolder.mAlarmSilence"+AlarmHolder.mAlarmSilence+"");
am.cancel(AlarmHolder.mAlarmSilence);
}
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, TestSwitch.getInstance().getNormal_time(), AlarmHolder.mAlarmNormal);
return null;
}
private static final class AlarmHolder {
static final PendingIntent mAlarmSilence = PendingIntent.getService(ApplicationContext.getInstance(),
0,
new Intent(ApplicationContext.getInstance(), GetRoundSilenceService.class),
0);
static final PendingIntent mAlarmNormal = PendingIntent.getService(ApplicationContext.getInstance(),
0, new
Intent(ApplicationContext.getInstance(), GetRoundNormalService.class),
0);
}
}
GetRoundSilenceService and GerRoundNormalService invoke start_am_normal() or start_am_silence; Anyone could help me? thanks

myIntent = new Intent(SetActivity.this, AlarmActivity.class);
pendingIntent = PendingIntent.getActivity(CellManageAddShowActivity.this,
id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.cancel();
alarmManager.cancel(pendingIntent);
These lines of code surely can help you remove/cancel the pending intent and alarm.
The main thing that you will need is:
Create pending intent with the same id and appropriate intent FLAG.
Cancel that pending intent.
Cancel the alarm using alarm manager.

#MKJParekh answer is correct, however I would like to add more information so that we all know what will work and what will not.
Lets say on activityA you create and set the AlarmManager to open activityC in 30 seconds, then on some other activity which can be any, we want to cancel that AlarmManager. Thus, we would do the following;
in activityA we create and set the AlarmManager;
//activityA
Intent myIntentA = new Intent(actvityA.this, activityB.class)
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent myPendingIntent = PendingIntent.getActivity(activityA.this, 0, myIntentA, PendingIntent.FLAG_ONE_SHOT);
//Calendar with the time we want to fire the Alarm
Calendar calendar = Calendar.getInstance(); // Get Current Time
calendar.add(Calendar.SECOND,30); //Fire Alarm in 30 seconds from Now.
((AlarmManager)getSystemService(ALARM_SERVICE)).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), myPendingIntent);
in Another Activity some time later we want to cancel such AlarmManager created in activityA which we have no access to. Lets call this current activity activityZ;
//activityZ
Intent myIntentZ = new Intent(activityZ.this, activityB.class);
PendingIntent pendingIntentZ = PendingIntent.getActivity(activityZ.this, 0, myIntentZ, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager)getSystemService(ALARM_SERVICE)).cancel(pendingIntentZ);
Some important points,
The context we provide in activityA in new Intent(context) and getActivity(context) are the same, however they do not have to match the activity from where we are canceling the AlarmManager, in this case activityZ has another context.
The class we want to open with the AlarmManager has to be the same in both activities new Intent (context, activityB.class), the requestCode which is an int must be the same, I used 0 for this example. Finally the flag has to be the same in both activities PendingIntent.FLAG_ONE_SHOT.
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); was used because PendingIntent.getActivity requires it if we are starting an activity outside of a context of an existing activity.

Related

Alarm notification keeps firing even if it is canceled from another activity

I set an alarm from activity A then in activity B I can delete and update the alarm set in activity A. Updating of alarm is working but delete doesn't, I've already tried some answer from here but nothing seems to work.
I set my alarms like this.
public void Alarms() {
for(eventlist_model model:arrayList)
{
int id=model.getEvent_id();
String type=model.getEvent_type();
String date=model.getEvent_date();
String time=model.getEvent_time();
String note=model.getEvent_note();
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd HH:mm");
try{
String sched=date+" "+time;
Date newSched=format.parse(sched);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(newSched);
if (calendar1.before(calendar))
calendar1.add(Calendar.DATE, 1);
Intent intent = new Intent(this, events_receiver.class).setAction("Dog_alarm");
intent.putExtra("type", type);
intent.putExtra("note", note);
intent.putExtra("id", id);
PendingIntent dog1 = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarm1 = (AlarmManager) getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= 19) {
alarm1.setExact(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), dog1);
} else {
alarm1.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), dog1);
}
}catch (Exception e)
{
e.printStackTrace();
}
}
}
then in activity B I use this to cancel the alarm
public void cancelTask()
{ int id=Integer.valueOf(eventid);
Intent intent = new Intent(update_task.this, events_receiver.class);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent task = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(task);
}
But it doesn't work and Im stuck here. Can anyone help me in this?
According to documentation of cancel method of AlarmManager:
void cancel (PendingIntent operation)
Remove any alarms with a matching Intent. Any alarm, of any type,
whose Intent matches this one (as defined by filterEquals(Intent)),
will be canceled.
It means if intentA detected to be equal withintentB, using filterEqauls Method, i.e. intentA.filterEquals(intentB)==true, then intentB in alarmanger can be used to cancel intentA which already set inside alarmManager.
filterEquals documentation notices:
boolean filterEquals (Intent other)
Determine if two intents are the same for the purposes of intent
resolution (filtering). That is, if their action, data, type, class,
and categories are the same. This does not compare any extra data
included in the intents.
It means it filterEquals does not care to extras inside intents to compare them but other paramters like Action should be exactly the same.
In your case, you've missed to call setAction in cancellation intent.
So you should change your cancelTask method like this:
public void cancelTask()
{ int id=Integer.valueOf(eventid);
Intent intent = new Intent(update_task.this, events_receiver.class);
intent.setAction("Dog_alarm");//<--- this is missed
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent task = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.cancel(task);
}

Android: How to stop repeating alarm without unsetting the alarm itself

I have an Android app where I need to trigger reminders everyday at the same time. The alarm must repeat every 5 minutes if ignored. If the user declares he read the reminder, by clicking an OK button, the alarm must stop repeating, until it is triggered the day after.
So, I want the alarm to stop repeating after the user's confirmation, and I read that with AlarmManager I should use the cancel() method. But I don't want to delete the alarm for future days, I just want it to stop repeating until next trigger.
In other words, I don't want the cancel() method to unset the alarm for the future days. Is it the default behavior of the cancel() method or do I have to cancel the alarm and then re-set it every time?
This is my code for setting the alarm:
public class AlarmSettingManager
{
private static Context context;
// Constructor
public AlarmSettingManager(Context c)
{
context = c;
}
private static class PrescriptionAlarmSetter extends AsyncTask<String, Void, Boolean>
{
SharedPrefManager sharedPrefManager = SharedPrefManager.getInstance(context);
#Override
protected Boolean doInBackground(String... strings)
{
// Get the list of prescriptions from SharedPreferences
if(!sharedPrefManager.getPrescrizioneList().equals(""))
{
try
{
JSONArray responseJsonArray = new JSONArray(sharedPrefManager.getPrescrizioneList());
int currentID = Constants.PRESCRIZIONE_ALARM_ID;
for(int j=0; j<responseJsonArray.length(); j++)
{
JSONObject singlePrescription = responseJsonArray.getJSONObject(j);
Prescrizione prescrizione = new Prescrizione
(
singlePrescription.getInt("id_prescrizione"),
singlePrescription.getInt("id_medico"),
singlePrescription.getInt("id_farmaco"),
singlePrescription.getInt("numero_pasticche"),
singlePrescription.getInt("totale_compresse"),
singlePrescription.getString("nome"),
singlePrescription.getString("ora_assunzione"),
singlePrescription.getString("posologia"),
singlePrescription.getString("suggerimenti")
);
// Start setting the alarm for current prescription
Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(
context.getApplicationContext(),
currentID,
alarmIntent,
PendingIntent.FLAG_CANCEL_CURRENT
);
// put the RequestCode ID as extra in order to identify which alarm is triggered
alarmIntent.putExtra("id", currentID);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// Specify the time to trigger the alarm
calendar.set(Calendar.HOUR_OF_DAY, prescrizione.getIntHour());
calendar.set(Calendar.MINUTE, prescrizione.getIntMinutes());
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Set the time interval (in milliseconds) to repeat the alarm if the previous one was ignored
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 300000L, pendingIntent);
currentID++;
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean b)
{
super.onPostExecute(b);
}
}
public boolean setAlarms()
{
AlarmSettingManager.PrescriptionAlarmSetter prescriptionAlarmSetter = new AlarmSettingManager.PrescriptionAlarmSetter();
prescriptionAlarmSetter.execute();
return true;
}
}
And this is the piece of code I'm going to adapt in order to cancel the alarm repeating:
Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(
context.getApplicationContext(),
currentID,
alarmIntent,
0
);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
Thanks.
At the time of cancelling alarm schedule a new alarm for the next day.
The intention of the "cancel" option is to remove the alarm.
Your application should add a new alarm just as the original was setup.
You can find a nice example of implementing a full alarm in Android at the following link, including how to re-add it on device reboot.
Repeat Alarm Example In Android Using AlarmManager

Alarm Manager and Pending Intent Cancel Not Working

I schedule Alarm from Activity like.
private AlarmManager mAlarmManager;
mAlarmManager = (AlarmManager) ACT_ActiveSession.getAppContext()
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(mContext, LocalNotification.class);
intent.putExtra("alertBody", "");
intent.putExtra(K.SESSIONID, "");
intent.putExtra("TIME", "");
intent.putExtra("BATCHNO","");
intent.putExtra("REQUEST_CODE", "");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
ACT_ActiveSession.getAppContext(), REQUEST_CODE, intent, 0);
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, finishTime,
pendingIntent);
// alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, finishTime,
// (1 * 1000), pendingIntent);
intent.putExtra("",""); only used for some task on BroadcastReceiver
And Cancel Alarm From Fragment
private AlarmManager mAlarmManager;
mAlarmManager = (AlarmManager) mActivity
.getSystemService(Context.ALARM_SERVICE);
Intent updateServiceIntent = new Intent(mActivity,
ACT_Home.class);
PendingIntent pendingUpdateIntent = PendingIntent.getBroadcast(
mActivity, REQUEST_CODE,
updateServiceIntent, 0);
pendingUpdateIntent.cancel();
// Cancel alarms
if (pendingUpdateIntent != null) {
mAlarmManager.cancel(pendingUpdateIntent);
Log.e("", "alaram canceled ");
} else {
Log.e("", "pendingUpdateIntent is null");
}
But Alarm Manager is not cancelled.
Here i change mActivity = MyActivity's static getApplicationContext(); and also change different Flags and different Context.
Also I refer many answer. But doesn't work any code. Link1 Link2 Link3
please give me solution as soon as possible.
and apologize for my bad English.
You create the alarm using this Intent:
Intent intent = new Intent(mContext, LocalNotification.class);
But you try to cancel it using this Intent:
Intent updateServiceIntent = new Intent(mActivity, ACT_Home.class);
These Intents do not match, so the cancel does nothing. If you want to cancel the alarm you need to use an Intent in the cancel call that matches the Intent you used to schedule the alarm.

How to cancel ongoing alarm in Android

I'm making an application in which I want to cancel an alarm(not set by my application) after few seconds.
What is the way to cancel alarm which may be set by any other application?
What I have is, notification posted on Android Notification Center when alarm triggers.
I read from android documentation that I need PendingIntent to cancel the triggered alarm. But how can I get PendingIntent in this case?
I noticed that I can get contentIntent from alarm notification,posted to the Android Notification Center. I tried to cancel alarm from this PendingIntent but did not succeed.
Any way to get PendingIntent of triggered alarm? Or/And to cancel alarm?
This trick is a little bit old, but it saves many developers.
Suppose in ActivityOne we start an AlarmManager like:
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnServiceReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 5290, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000, LOCAL_SERVICE_PERIOD, pi);
To cancel this AlarmManager in any other Activity/Broadcastreceiver/Service we have to remember some of its informations.
1: Context: The context used by the AlarmManager followed by its PendingIntent.
2: PendingIntent ID: getBroadcast(context, 5290, i, 0); .It makes the Pi unique which is mostly important.
So we have to save the PendingIntent id in a SharedPreference to confirm at the time of canceling.
Now the Context used by AlarmManager .
In same Activity( ActivityOne) we have to create a global Context which holds the original one. like:
//Define it globaly in ActivityOne
private static Context mContext;
//create a public static method which holds the current context and share
public static Context getActivityOneContext() {
return ActivityOne.mContext;
}
//initialize it by assigning application context in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxx);
mContext = getApplicationContext();
//Or if this is a BroadCastReceiver ..use the current context and do same in onReceive()
//OnBootReceiver.mContext = context.getApplicationContext();
Now you can cancel the AlarmManager anywhere of the application..
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent stopIntent = new Intent(ActivityOne.getActivityOneContext, OnServiceReceiver.class);
PendingIntent stopPI = PendingIntent.getBroadcast(ActivityOne.getActivityOneContext, 5290, stopIntent, 0);
mgr.cancel(stopPI);

How to cancel an alarm in android?

I am trying to cancel all alarms other an intent
i am sending stuff in using
new gofile(this).setSilent(mRowId, mCalendar);
that then goes to gofile
public class gofile {
private Context goon
private AlarmManager alarm;
public gofile(Context goon){
mContext = context;
alarm = (AlarmManager)goon.getSystemService(Context.ALARM_SERVICE);
}
public void setSilent(Long Id, Calendar when){
Intent i = new Intent(gon, anohterclass.class);
PendingIntent go = PendingIntent.getBroadcast(goon, 0 , i, PendingIntent.FLAG_ONE_SHOT);
alarm.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), go);
how would i cancel the alarms from another file?
You must use the cancel method, and you must make sure the PendingIntent contains the information than the one you used to set the alarm.

Categories

Resources