我已经使用了带有 Geofences 的 Android 教程,显然,当应用程序关闭时它不起作用。因此,在四处搜索之后,我注意到 SO 上的用户 b-ryce 使用了 BroadcastReceiver,因此即使应用程序未处于活动状态,地理围栏也会被触发(他的 SO 问题的链接)。
当我移到注册位置外/内时,我无法强制触发地理围栏。这是我的程序:
/**
* GeoLocation library
*/
mGeoLocation = new GeoLocation(sInstance);
/**
* mReceiver init
*/
mReceiver = new Receiver();
sInstance.registerReceiver(mReceiver, mReceiver.createIntentFilter());
在 GeoLocation 类中:
/*
* Create a PendingIntent that triggers an IntentService in your
* app when a geofence transition occurs.
*/
protected PendingIntent getTransitionPendingIntent() {
if (mGeoPendingIntent != null) {
return mGeoPendingIntent;
}
else {
// Create an explicit Intent
// Intent intent = new Intent(mContext,
// ReceiveTransitionsIntentService.class);
Intent intent = new Intent(getClass().getPackage().getName() + ".GEOFENCE_RECEIVE");
/**
* Return the PendingIntent
*/
return PendingIntent.getBroadcast(
mContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
以下是我创建新地理围栏的方法:
Geofence fence = new Geofence.Builder()
.setRequestId(hashCode)
// when entering this geofence
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(
Double.parseDouble(single.getSetting("latitude")),
Double.parseDouble(single.getSetting("longitude")),
Float.parseFloat(single.getSetting("radius")) // radius in meters
)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofences.add(fence);
数组被填充,我们在 Geofence 类中调用 AddGeofences 方法
mGeoLocation.AddGeofences(mGeofences);
接收者类的 AndroidManifest.xml:
<!-- RECEIVER -->
<receiver android:name=".Receiver" >
</receiver>
接收器类应该只在地理围栏触发时记录
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("sfen", "Broadcast recieved "+ action +" but not needed.");
}
问题是,只有当我在我选择位置的应用程序中打开地图时,才会触发地理围栏。关闭应用程序(在后台运行)不会触发任何东西,地理围栏转换也不会触发任何东西。
有人可以告诉我我做错了什么吗?