In my app, I would like to delete all pendingIntent in my alarmManager.
Is possible to do a for() to delete all?
Try this.
Android: Get all PendingIntents set with AlarmManager
To cancel all alarm, first you have to find all the pending intent for that and cancel alarm using that.
If it is helpful to you than don't miss to accept this as your answer.
// set up alarm
List<PendingIntent> mPendingIntentList = new ArrayList<PendingIntent>();
Intent alarmIntent = new Intent(getApplicationContext(),Receiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent displayIntent = PendingIntent.getBroadcast(getContext(), 0, alarmIntent, 0);
// add pending intent in list
mPendingIntentList.add(displayIntent );
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDateTime, displayIntent);
//cancel all alarms
for(int idx = 0 ; idx < mPendingIntentList.size() ; idx++){
alarmManager .cancel(mPendingIntentList.get(idx));
}
See AlarmManager.cancel(PendingIntent)
Create a PendingIntent matching the intent(s) you wish to cancel. Calling the above function once, will cancel all matching alarms
.
Related
I am making an alarm app in which the alarm can be set with a toggle button. The code works in ADV, but if I test it on a real device, the the App closes imediatly after settting the alarm once and then turning it off. Also the alarm does not turn off.
(button press alarmOn -> alarm is on,
button press alarmOff-> app closes + alarm is still on)
mStartBtn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long time;
if (((ToggleButton) view).isChecked()){ //if button is on
Intent intent = new Intent(MainActivity.this, AlarmReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker1.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker1.getCurrentMinute());
time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
if (System.currentTimeMillis() > time) {
if (calendar.AM_PM == 0)
time = time + (1000 * 60 * 60 * 12);
else
time = time + (1000 * 60 * 60 * 24);
}
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); //sets the alarm
}else{ //if button is off
am.cancel(pendingIntent);
}
}
});
Thank you for helping,
Florian
Your app is basically crashing. Maybe because you are passing null to am.cancel(pendingIntent)//pendingIntent might be null here.
Try moving PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT); outside the if condition. If that is not the case then check AlarmReceiverActivity for crashes.
I'm trying to set several alarms with my app, and cancel them upon request.
I've read a lot of topics about the same, and went through the documentation, but it seems like it doesn't work.
Documentation says that cancel will try to find an intent that matches the one I provide with 'filterEquals'('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.')
I'm providing same action, data, type, class, and category, so why does it not work?
Create alarm:
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 30000;
Intent intent = new Intent(getApplicationContext(), Broadcast.class);
intent.putExtra("alarmTime",alarmTime);
intent.putExtra("reminder1",reminder1);
intent.putExtra("reminder2",reminder2);
intent.putExtra("title",title);
intent.putExtra("message",message);
intent.putExtra("vibrate",vibrate);
intent.putExtra("sound",sound);
intent.putExtra("name",name);
//Create _id from data input. is unique
int _id = 0;
for (char i: name.toCharArray()){
_id += Character.getNumericValue(i);
}
for (char i:title.toCharArray()){
_id += Character.getNumericValue(i);
}
for (char i:message.toCharArray()){
_id += Character.getNumericValue(i);
}
_id += (int) alarmTime.getTime();
_id += (int) reminder1.getTime();
_id += (int) reminder2.getTime();
Log.e("ALARMS", "Creating alarm with id: "+_id);
intent.setData(Uri.parse("custom://" + _id));
intent.setAction(String.valueOf(_id));
PendingIntent pendingUpdateIntent = PendingIntent.getBroadcast(getApplicationContext(), _id, intent, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval, pendingUpdateIntent);
Cancel alarm
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), Broadcast.class);
intent.putExtra("alarmTime",alarmTime);
intent.putExtra("reminder1",reminder1);
intent.putExtra("reminder2",reminder2);
intent.putExtra("title",title);
intent.putExtra("message",message);
intent.putExtra("vibrate",vibrate);
intent.putExtra("sound",sound);
intent.putExtra("name",name);
int _id = 0;
for (char i:name.toCharArray()){
_id += Character.getNumericValue(i);
}
for (char i:title.toCharArray()){
_id += Character.getNumericValue(i);
}
for (char i:message.toCharArray()){
_id += Character.getNumericValue(i);
}
_id += (int) alarmTime.getTime();
_id += (int) reminder1.getTime();
_id += (int) reminder2.getTime();
intent.setData(Uri.parse("custom://" + _id));
intent.setAction(String.valueOf(_id));
PendingIntent pendingUpdateIntent = PendingIntent.getBroadcast(getApplicationContext(), _id, intent, 0);
Log.e("ALARMS", "Cancelling alarm with id: "+_id);
// Cancel alarms
try {
manager.cancel(pendingUpdateIntent);
} catch (Exception e) {
Log.e("ALARMS", "AlarmManager update was not canceled. " + e.toString());
}
So I call 3 times the create alarm with different parameters, so my _id is different each time.
Then I call 3 times the cancel alarm and the ids generated match for each alarm upon create and cancel.
So the cancel runs but my alarms still get fired.
My alarms trigger a broadcast receiver that will output a notification per alarm.
I forgot to mention that I tried with different flags for the PendingIntent but none work (FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT)
Seems like I was feeding different dates to the alarms, and the _id's were different by a couple of numbers (start and finish were the same), this resulted on calling a cancel on _id values that were different and not working.
Changed the way I generate the _id to exclude the dates (which I generated with new Date()) and not it works
By bad, I didn't see it.
I am not a developer, and am trying to get some sample code working nicely.
The API I am running against, is not 100% compatible with my code I am using.(API15).
Would anyone be able to help me reformat this code to work with the newer style builder notifications?
(I had a try, but cant work out the right way of doing it based on the question linked)
{
Notification notification = new Notification(R.drawable.ic_launcher, "Robot service running", System.currentTimeMillis());
notification.setLatestEventInfo(this, "Robot Service", "Click to stop", PendingIntent.getService(this, 0, new Intent("stop", null, this, this.getClass()), 0));
notification.flags |= Notification.FLAG_ONGOING_EVENT;
nm.notify(0, notification);
}
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
For more detail use below link:
http://developer.android.com/reference/android/app/Notification.Builder.html
I have been developing an Android application and I need to execute 1 task every hour. I uses the following code for it:
private static final long ALARM_PERIOD = 1000L;
public static void initAlarmManager(Context context) {
Editor editor=PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean(context.getString(R.string.terminate_key), true).commit();
AlarmManager manager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmEventReceiver.class);
PendingIntent receiver = PendingIntent.getBroadcast(context, 0, i, 0);
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), ALARM_PERIOD, receiver);
}
It works for me, but my client tells me that the task works only 1 time and won't work 1 hour. Where have I made a mistake? Please, tell me. Thank you.
According to your code, ALARM_PERIOD is 1000L, as repeating interval. So I doubt the alarm will set of in every 1000 milliseconds.
if you are setting repeating interval for every hour, it should be 3600000L.
And take note that if the phone is restarted, your alarm manager will no longer work unless you start again.
Here is the my Code:
private void setAlarmManager() {
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long l = new Date().getTime();
if (l < new Date().getTime()) {
l += 86400000; // start at next 24 hour
}
am.setRepeating(AlarmManager.RTC_WAKEUP, l, 86400000, sender); // 86400000
}
Have you added receiver tag in application tag in manifest.xml
<receiver android:name=".AlarmReceiver" android:process=":remote"/>
Instead of Alram-Manager I recommended you to use Android-TimerTask
The TimerTask class represents a task to run at a specified time. The task may be run once or repeatedly. Its perfect suits for your requirements.
Try by modifying your code by changing your setRepeating() method like this
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime(), SystemClock.elapsedRealtime()+(60*60*1000), receiver);
OR
Test this it is repeating for every minute
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,Calendar.getInstance().getTimeInMillis(), Calendar.getInstance().getTimeInMillis()+(1*60*1000), receiver);
What I'm doing is adding different proximity alerts with a unique ID as an extra and it's not working -
for (int i = 0; i < latArray.size(); i++)
{
Bundle extra = new Bundle();
extra.putInt("UID", i);
Intent intent = new Intent(IntentToFire);
intent.putExtra("Blob", extra);
PendingIntent proximityIntent = PendingIntent.getBroadcast(this,-1 , intent, 0);
LocationManager locationManager =
Log.i("Picture:","Location img:"+GetLocation.imgArray.get(i));
Log.i("Potatoo:", "Lat :"+latArray.get(i)+" Lng :"+lngArray.get(i));
locationManager.addProximityAlert(Double.valueOf(latArray.get(i)), Double.valueOf(lngArray.get(i)), radius,expiration,proximityIntent);
}
And then on the broadcast receiver I'm putting this code -
flag = intent.getBundleExtra("blob").getInt("UID");
Every time I got to print flag, I just get an error. An ideas?
Try to use the FLAG_UPDATE_CURRENT:
PendingIntent.getBroadcast(this,-1 , intent, PendingIntent.FLAG_UPDATE_CURRENT);
I found it easiest is to encode data in the data-uri with proximity alerts on the Intent that is included in the pending intent, e.x.:
geo:<lat>,<lon>?id=<your id>
You can use your own protocol part though (geo is used by google maps AFAIK). No caching problems for me (seems you get a cached/old/wrong PendingIntent).