我为每个地图标记设置了我的地图和接近警报,这里我将lat和long传递给地址,并将地名添加到添加接近警报方法:
if(alerts==true)
{
addProximityAlert(l1, l2, place);
}
添加近距离警报方法:
//The following sets up proximity alerts, getting a unique id for each one
private void addProximityAlert(Double latitude, Double longitude, String tit) {
Intent intent = new Intent(PROX_ALERT_INTENT);
intent.putExtra("name", tit);
intent.putExtra("id", alertid);
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, alertid, intent, PendingIntent.FLAG_ONE_SHOT);
lm.addProximityAlert(latitude, longitude, POINT_RADIUS, PROX_ALERT_EXPIRATION,proximityIntent );
alertid++;
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT );
registerReceiver(new ProximityIntentReceiver(), filter);
}
以下是接近警报类:
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
}else {
Log.d(getClass().getSimpleName(), "exiting");
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, Map.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "Proximity Alert!", "You are approaching: " +intent.getStringExtra("name"), pendingIntent);
notificationManager.notify( intent.getIntExtra("id", -1), notification);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.icon = R.drawable.ic_launcher;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.CYAN;
notification.ledOnMS = 15000;
notification.ledOffMS = 15000;
return notification;
}
}
第一次设置地图alertid为0,并且有四个地图标记,并且设置了四个接近警报,并且工作正常。当离开地图并返回时,它再次设置,alertid重置为0,但警报再次添加,因此8个警报响起,每次添加4个新警报。我想通过将alertid重置为0,再次重新创建它们会覆盖之前的那些,因为它们有一个id,但这显然不会发生。任何人都可以看到它们是如何构建的,并且可能告诉我如何确保它们仅为每次设置创建一次?
答案 0 :(得分:2)
我想你应该保留某种List,你可以保留所有警报的意图,以避免添加它们两次或几次。另外,根据您的使用场景,您应该在通知后将其删除:
lm.removeProximityAlert(PendingIntent intent)
但更有可能是你多次注册了BroadcastReceiver :) 尝试只调用一次(而不是每次添加警报时):
registerReceiver(new ProximityIntentReceiver(), filter);