[英]Proximity alert firing twice after removing and re-adding
我有接近警報的問題。 我在我的Android應用程序上有設置,用戶可以禁用/啟用某些位置的近距離警報。 當他們禁用接近警報時,一切都很好,他們將不會得到通知,但如果他們禁用並重新啟用接近警報,它會再次添加,當他們到達某個位置時他們會收到兩次通知,依此類推。 所以基本上每次重新啟用它時,它都會創建一個新的接近警報。
這是我用來刪除近距離警報的代碼:
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);
}
這是我用來添加接近警報的代碼:
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);
}
我對FLAG_CANCEL_CURRENT
理解是它告訴系統舊的待處理意圖不再有效,它應該取消它然后創建一個新的意圖。 如果我錯了,請糾正我。 我相信,這就是為什么每次取消和創建都要復制Proximity Alerts的原因。
解析度:
在你的removeProximityAlert
我會更改以下行
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
至:
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
FLAG_UPDATE_CURRENT
返回創建的現有文件(如果有)。 cancel()
應該為你處理剩下的事情。
編輯
如果我將cancel()
分成一個單獨的行,我不會得到任何錯誤。 嘗試這個:
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
proximityIntent.cancel();
問題是每次添加警報時都要注冊接收器。 你應該只注冊一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.