简体   繁体   中英

Proximity alert firing twice after removing and re-adding

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);
}

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();

The problem is that you're registering the receiver each time you add the alarm. You should register it only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM