iOS SDK拥有出色的区域监控功能。我需要在Android中实现类似的功能,我认为我们有两种选择:Geofencing和LocationManager。
Geofencing有非常整洁的示例和错误处理,因此我更喜欢使用LocationManager。在LocationManager中一切都很好,除了一个问题。如果将您当前的位置添加为ProximityAlert,则会立即触发“ENTERING”,但这是我的当前位置,并不意味着我已进入该区域。因此,如果我在该区域内(即使我没有移动),每次启动应用程序时它都会触发“ENTERING”。
我该如何解决这个问题并仅在用户真正进入该区域时触发事件?
以下是我为我的位置添加PendingIntents的方式:
LocationManager locationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
for(Place p : places)
{
Log.e("location", p.location);
Bundle extras = new Bundle();
extras.putString("name", p.displayName);
extras.putString("id", p.id);
Intent intent = new Intent(CommandTypes.PROX_ALERT_INTENT);
intent.putExtra(CommandTypes.PROX_ALERT_INTENT, extras);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,Integer.parseInt(p.id), intent,PendingIntent.FLAG_CANCEL_CURRENT);
float radius = 50f;
locationManager.addProximityAlert(p.lat,
p.lon, radius, 1000000, pendingIntent);
}
接收器
public class ProximityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String key = LocationManager.KEY_PROXIMITY_ENTERING;
final Boolean entering = intent.getBooleanExtra(key, false);
Bundle b = intent.getBundleExtra(CommandTypes.PROX_ALERT_INTENT);
String id = b.getString("id");
Log.e("here" + id, "here");
if (entering) {
Log.e(TAG,"entering");
} else {
Log.e(TAG,"leaving");
}
}
清单文件
<receiver android:name=".ProximityReceiver">
<intent-filter>
<action android:name="ACTION_PROXIMITY_ALERT" />
</intent-filter>
</receiver>
非常感谢。
PS:iOS没有这个问题,并且他们的文档已经解释了。
在授权应用程序注册后,地理区域的监视将立即开始。但是,不要期望立即收到事件。只有边界穿越才会生成事件。因此,如果在注册时用户的位置已经在区域内,位置管理器不会自动生成事件。相反,您的应用程序必须等待用户越过区域边界,然后才会生成并发送事件到委托。话虽如此,您可以使用CLLocationManager类的requestStateForRegion:方法检查用户是否已经在区域的边界内。