Reputation: 107
I am having a problem with the proximity alert. I have settings on my android application where users can disable/enable proximity alert of some locations. When they disable the proximity alert everything works great and they will not be notified, but if they disable and the re-enable the proximity alert, it adds again and they will get a notification twice when they reach a location and so on. So basically every time they re-enable it, it creates a new proximity alert.
This is the code I use to remove the proximity alert:
private void removeProximityAlert(int id) {
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
Intent intent = new Intent(PROX_ALERT_INTENT + id);
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
manager.removeProximityAlert(proximityIntent);
}
And this is the code that I use to add a proximity alert:
private void addProximityAlert(double latitude, double longitude, int id, int radius, String title) {
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
Intent intent = new Intent(PROX_ALERT_INTENT + id);
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
manager.addProximityAlert(
latitude,
longitude,
radius,
-1,
proximityIntent
);
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT + id);
registerReceiver(new ProximityIntentReceiver(id, title), filter);
}
Upvotes: 4
Views: 1183
Reputation: 1233
The problem is that you're registering the receiver each time you add the alarm. You should register it only once.
Upvotes: 0
Reputation: 8925
My understanding of FLAG_CANCEL_CURRENT
is that it tells the system that the old pending intent is no longer valid and it should cancel it and then create a fresh one. Correct me if I am wrong. This, I believe, is why you are duplicating Proximity Alerts with each cancel and creation.
Resolution:
In your removeProximityAlert
I would change the following line
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
to:
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
FLAG_UPDATE_CURRENT
returns the existing one created, if any. cancel()
should take care of the rest for you.
Edit
If I break the cancel()
into a separate line I don't get any errors. Try this:
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
proximityIntent.cancel();
Upvotes: 1