2017-07-18 100 views
0

試圖監視設備是否進入或退出地理圍欄。但有時即使設備沒有移動,它也會收到進入或退出事件。代碼片段如下。如何獲取準確的地理圍欄事件

使用

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

GPS信號設備之間變化,如果你的設備的GPS信號不好也表現不同(如果你是一個建築物或類似的東西在裏面),你會看到的GPS位置跳來跳去,不不變。 目前沒有好方法可以在100%的情況下獲得準確的位置。

+0

謝謝Sagi Mymon!但是可能有一些方法,因爲一些應用程序似乎可以在LocationServices中可靠地工作。只是想知道如果有人可能知道。 – lannyf