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.
Related
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
I have an app that allows a user to create a reminder to alert them in the future. The issue I am running into, is that as a user creates more than one reminder, the pending intent only triggers on the latest one created, with the earliest reminder content to display, ie:
Task 1, set for 4pm
Task 2, set for 5pm
Task 3, set for 6pm
No reminder will appear until 6pm, which will display Task 1.
I believe it has to due with the lack of uniqueness of the PendingIntent:
public class ReminderManager {
private Context mContext;
private AlarmManager mAlarmManager;
public ReminderManager(Context context) {
mContext = context;
mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
}
public void setReminder(Long taskId, Calendar when) {
Intent i = new Intent(mContext, OnAlarmReceiver.class);
i.putExtra(RemindersDbAdapter.KEY_ROWID, (long)taskId);
PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_ONE_SHOT);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi);
}
}
How can I ensure that each reminder is unique and gets its correct time on time?
You need to provide something other than 0 for the requestCode param. Try making it a unique ID for each request.
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);
I trying to put notification for my todo list. The notification works, but for only 1 item, how do I set for multiple notifications. If I put two items for notification, only the last one that I set will show up a notification. Here is my code for the alarm task.
public class AlarmTask implements Runnable{
// The date selected for the alarm
private final Calendar date;
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
public AlarmTask(Context context, Calendar date) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.date = date;
}
#Override
public void run() {
// Request to start service when the alarm date is upon us
// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
Intent intent = new Intent(context, NotifyService.class);
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);
}
}
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.