The proximity warning is triggered twice after deletion and re-addition

I have a problem with proximity alert. I have settings in an Android app where users can turn off / turn on proximity alerts in some places. When they turn off the proximity alert, everything works fine and they won’t be notified, but if they are turned off and activate the proximity alert again, it will add again and they will receive a notification twice when they reach the location and so on. Therefore, every time they re-activate it, it creates a new proximity alert.

This is the code I use to remove the proximity warning:

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 proximity warning:

 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); } 
+4
source share
2 answers

My understanding of FLAG_CANCEL_CURRENT is that it tells the system that the old pending intent is no longer valid, and that it must cancel it and then create a new one. Correct me if I am wrong. This, I believe, is the reason that you duplicate proximity alerts with each cancellation and creation.

Resolution:

In your removeProximityAlert I would change the following line

 PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT); 

in

 PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT).cancel(); 

FLAG_UPDATE_CURRENT returns an existing one, if any. cancel() should take care of everything else.


Edit

If I split cancel() on a separate line, I get no errors. Try the following:

 PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); proximityIntent.cancel(); 
+1
source

The problem is that you register the receiver every time you add an alarm. You must register it only once.

0
source

Source: https://habr.com/ru/post/1444815/


All Articles