我试图在用户到达指定区域时向其显示推送提醒。
所以我从https://developer.android.com/training/location/geofencing开始编写我的应用程序。
如果我的应用程序正在运行并跟踪用户的位置,则它可以完美地工作。
例如,如果我启动Google地图,则它也会跟踪我的位置。 推送将出现。
但是,如果我关闭应用程序,则推送将不会出现,因此如果没有应用程序跟踪我的位置,则无法检测到地理围栏。
这是正常的吗? 如何始终使其正常工作? 如果需要前台服务跟踪您的位置,那么地理围栏有什么意义?
public void createGeofenceAlerts(LatLng latLng, int radius) {
final Geofence enter = buildGeofence(ID_ENTER, latLng, radius, Geofence.GEOFENCE_TRANSITION_ENTER);
final Geofence exit = buildGeofence(ID_EXIT, latLng, radius, Geofence.GEOFENCE_TRANSITION_EXIT);
final Geofence dwell = buildGeofence(ID_DWELL, latLng, radius, Geofence.GEOFENCE_TRANSITION_DWELL);
GeofencingRequest request = new GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofence(enter)
.addGeofence(exit)
.addGeofence(dwell)
.build();
fencingClient.addGeofences(request, getGeofencePendingIntent()).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Timber.i("succes");
Toast.makeText(mContext, "Geofence added", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Timber.e(e,"failure");
Toast.makeText(mContext, "Geofence ERROR", Toast.LENGTH_LONG).show();
}
});
}
private PendingIntent getGeofencePendingIntent() {
Intent intent = new Intent(mContext, GeofenceTransitionsIntentService.class);
PendingIntent pending = PendingIntent.getService(
mContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
return pending;
}
private Geofence buildGeofence(String id, LatLng center, int radius, int transitionType) {
Geofence.Builder builder = new Geofence.Builder()
// 1
.setRequestId(id)
// 2
.setCircularRegion(
center.getLatitude(),
center.getLongitude(),
radius)
// 3
.setTransitionTypes(transitionType)
// 4
.setExpirationDuration(Geofence.NEVER_EXPIRE);
if (transitionType == Geofence.GEOFENCE_TRANSITION_DWELL) {
builder.setLoiteringDelay(LOITERING_DELAY);
}
return builder.build();
}