使用相同的广播设置2个接近警报

时间:2010-07-21 10:50:16

标签: android gps alert broadcastreceiver

我以这种方式创建了一个接近警报

    private void setProximityAlert(float radius, double lat, double lng, String place)
{
    long expiration = -1;
    LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Intent intent = new Intent(TREASURE_PROXIMITY_ALERT);
    intent.putExtra("lat", lat);
    intent.putExtra("lng", lng);
    intent.putExtra("place", place);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), -1, intent, 0);   
    locManager.addProximityAlert(lat, lng, radius, expiration, pendingIntent);
}

在我的活动中,我以这种方式注册了接收器

    IntentFilter intentFilter = new IntentFilter(TREASURE_PROXIMITY_ALERT);
    registerReceiver(new ProximityIntentReceiver(), intentFilter);
    setProximityAlert(10, 45.150344, 9.999815, "POINT1");

我的广播接收器被正确调用。 所以现在,我想添加另一个接近警报,是否可能?我希望2接近警报调用相同的boadcast接收器。 我做了这个:

    IntentFilter intentFilter1 = new IntentFilter(TREASURE_PROXIMITY_ALERT1);
    registerReceiver(new ProximityIntentReceiver(), intentFilter1);        
    setProximityAlert(200f, 45.143848, 10.039741, "POINT2");

但它不起作用,没有任何反应。我现在真的很喜欢它,我想知道它是否正确。我的意图是触发2个警报,一个是GPS获取位置POINT1而另一个是POINT2位置。 欢迎任何帮助。

1 个答案:

答案 0 :(得分:6)

您需要使用任何唯一的setAction,以便系统将两个意图视为不同,否则将倾向于重用第一个意图。

我有这段代码:

Intent intent = new Intent(this,PlacesProximityHandlerService.class);
intent.setAction("foo"+objPlace.getId());
intent.putExtra(Poi._ID, objPlace.getId());
intent.putExtra(Poi.LAT, objPlace.getLat());
intent.putExtra(Poi.LON, objPlace.getLon());
PendingIntent sender = PendingIntent.getService(this,0, intent, 0);
LocationUtils.addProximity(this, objPlace.getLat(),objPlace.getLon(), objPlace.getError(), -1,sender);

另请注意,接近警报的工作有点棘手。

用户根据您设置的信号精度和半径输入热ZONE1。输入= true ZONE1会触发广播。如果您输入与当前区域重叠的另一个区域ZONE2,则当您仍在ZONE1中时,您不会收到警报。 您必须离开ZONE1,因此广播将再次触发,输入= false。所以一旦你离开ZONE1,如果你到达ZONE2,它将发射广播进入=真ZONE2。

我已经测试过,它运行得很好。从市场中获取Location Spoofer免费应用并模拟手机的位置。您还需要在手机设置中启用模拟位置。并为您的应用程序添加其他权限:

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

我会做什么,将我的位置设置在远离我的地方,可能是格陵兰岛,然后在触发ZONE1的区域设置位置,广播应该开火。然后再将我的位置设置为Greeland,并设置触发ZONE2的位置,广播应该触发。

输入标志可以来自意图附加

Bundle b = intent.getExtras();
Boolean entering = (Boolean) b.get(android.location.LocationManager.KEY_PROXIMITY_ENTERING);

我使用上述代码为100个POI设置了接近警报,并且一切正常。