2017-05-18 24 views
1

我有一個Android應用程序,我使用FusedLocationApi來獲取用戶的位置更新。爲什麼android FusedLocationApi在幾毫秒的時間內廣播相同的位置?

以下是該場景: 1.我有一個單獨的Watcher類,在該類中我定義了即使在應用程序處於後臺時也可以獲取位置的意圖。以下是代碼:

private PendingIntent pendingIntent; 
    private Watcher() { 
     Intent locationIntent = new Intent(context, Receiver.class); 
     pendingIntent = PendingIntent.getBroadcast(
        context, 007 /*requestcode*/, locationIntent, 
     PendingIntent.FLAG_UPDATE_CURRENT); 
    } 

然後,當我已經成功連接位置的服務,我請求位置更新:

LocationServices.FusedLocationApi. 
        requestLocationUpdates(googleApiClient, locationRequest, pendingIntent); 

現在,每當延伸WakefulBroadcastReceiver接收器類獲取位置更新,它開始Service.class。服務類擴展了IntentService。 以下是代碼:

@Override 
synchronized protected void onHandleIntent(final Intent intent) { 
if(LocationResult.hasResult(intent)) { 
    LocationResult locationResult= LocationResult.extractResult(intent); 
    Location location = locationResult.getLastLocation(); 
    printLocation(location); 
} 

所以我的問題是,由於上述步驟,爲什麼onHandleIntent得到爲期5毫秒內喚醒由LocationReceiver多次。 lat,lng和準確性都是一樣的。我已經定義了

setFastestInterval(5 seconds); and 
setInterval(1 minute); 

另外,位置精度是BALANCED_POWER_ACCURACY;

在我的應用程序中,

LocationServices.FusedLocationApi. 
        requestLocationUpdates(googleApiClient, locationRequest, pendingIntent); 

也被多次調用。但根據文檔:「任何以前註冊的具有相同PendingIntent(由equals(Object)定義)的請求將被此請求所取代。」我正在使用相同的pendingIntent對象來調用requestLocationUpdates。

在此先感謝。

回答

0

嗨Kanika你可以在傳遞你的位置請求對象之前設置最小位移,這將有助於你獲得更新,只有當你有一定的最小位移。你可以使用下面的方法來做同樣的事情。

setSmallestDisplacement(float smallestDisplacementMeters) 

另外FYI API參考鏈路,https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest

+0

嘿阿洛克,感謝響應。我試過了,仍然在幾毫秒內得到了更新:以下是日誌: 1)05-17 21:33:04.654 2303-3697關鍵位置更改爲:37.37984540,-122.06425810; 2) 05-17 21:33:07.474 2303-3841 /重要位置更改爲:37.37984000,-122.06452450; 3) 05-17 21:33:15.794 2303-3866 /關鍵位置更改爲:37.37984000,-122.06452450 – Kanika

+0

嘗試爲位移指定一個較大的值,例如100或1000,看看您是否仍然遇到同樣的問題? – Alok

+0

試過了,依然如此。你認爲pendingIntent沒有被足夠快地取代。因爲我在幾毫秒的時間內多次調用requestLocationUpdates()? – Kanika

相關問題