我曾经使用了与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.");
}
问题在于,地理围栏仅在我打开应用程序内的地图并选择位置时触发。关闭应用程序(在后台运行)不会触发任何事件,地理围栏转换也不会触发任何事件。
有人可以告诉我我做错了什么吗?