ios sdk 有很好的区域监控功能。我在android中需要类似的东西,我认为我们有两种选择。地理围栏和 LocationManager。
地理围栏有非常整洁的示例和错误,所以我更喜欢 LocationManager。除了一个之外,Everyting 在 LocationManager 中都可以正常工作。如果您将当前位置添加为 ProximityAlert ,它会立即触发“ENTERING”,但这是我当前的位置,并不意味着我进入了该区域。因此,如果我在区域内,每次启动应用程序时都会触发“ENTERING”。(即使我没有移动)
只有当用户真正进入该区域时,我才能解决这个问题并触发事件?
这是我为我的位置添加 PeddingIntents 的方式。
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: 方法来检查用户是否已经在区域边界内。