尝试监控设备进入或退出地理围栏。但有时它会收到进入或退出事件,即使设备没有移动。代码片段如下。
使用
后也注意到了lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
创建地理围栏,然后在
void onLocationChanged(Location location)
并使用更新的位置来获取用于地理围栏的位置之间的距离,似乎也不准确。就像在从位置#1创建地理围栏后走了几步之后,onLocationChanged()返回位置#2并且distanceTo()返回超过200米的显示。
还注意到即使设备在桌面上没有移动,onLocationChanged(位置位置)也会在某个时间返回不同的位置。
我想这可能取决于提供商,但测试是在wifi覆盖范围内。也许它是如何运作的。
但是,如果要求更准确或更细致,是否有不同或更好的方法来获得更准确的地理围栏事件或准确的当前位置?
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
createGeofence(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()));
创建地理围栏后,即使设备放在桌面上而不移动,它也会定期收到Geofence.GEOFENCE_TRANSITION_ENTER和Geofence.GEOFENCE_TRANSITION_EXIT。有时它会在没有事件的情况下保持静止,但如果略微移动设备,它将收到这些事件。
private void createGeofence(LatLng latlng) {
GeofencingClient mGeofencingClient; mGeofencingClient = LocationServices.getGeofencingClient(this);
Geofence geofence = makeOneGeofence(GEOFENCE_REQUEST_ID, latlng, 150f);
GeofencingRequest geofenceRequest = createGeofenceRequest(geofence);
LocationServices.GeofencingApi.addGeofences(
googleApiClient,
geofenceRequest,
getGeofencePendingIntent()
).setResultCallback(this);
}
Geofence makeOneGeofence(String reqestId, LatLng latLng, float radius) {
return new Geofence.Builder()
.setRequestId(reqestId)
.setCircularRegion(
latLng.latitude,
latLng.longitude,
radius //radius, meters
).setExpirationDuration(60 * 60 * 1000) //1 hr
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_DWELL |
Geofence.GEOFENCE_TRANSITION_EXIT)
.setLoiteringDelay(500000) // 500 secs, after user enters a geofence if the user stays inside during this period of time
.build();
}
private GeofencingRequest createGeofenceRequest(Geofence geofence) {
return new GeofencingRequest.Builder()
.setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER | GeofencingRequest.INITIAL_TRIGGER_DWELL )
.addGeofence( geofence )
.build();
}
private final int GEOFENCE_REQUEST_CODE = 0;
private PendingIntent getGeofencePendingIntent() {
if ( mGeofencePendingIntent != null )
return mGeofencePendingIntent;
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(
this, GEOFENCE_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
答案 0 :(得分:0)
GPS信号在不同设备之间变化,如果您的设备的GPS信号不好(如果您在建筑物内或类似的地方)也会表现不同,您会看到GPS位置在跳跃并且不是恒定的。 目前,在100%的情况下,没有很好的方法来获得准确的位置。