当我使用geo fix lng lat命令时,我的应用程序不会发现位置已更改。我的简化代码如下所示:
if (googleApiClient.isConnected()) {
Location lastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastKnownLocation!= null){
Log.d("Log", "Lat: " + lastKnownLocation.getLatitude());
Log.d("Log", "Lng: " + lastKnownLocation.getLongitude());
} else {
Log.d("Log", "No location detected");
}
}
googleApiClient:
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
因此,对于包含该代码运行的活动,我可以发送命令“geo fix 10 10”并重新加载该代码(通过刷新按钮),但它仍将记录 “没有检测到位置”
但是,如果我在模拟器中打开Google地图应用程序,然后返回我的应用程序并再次点击刷新它将输出: “Lat:10” “lng:10”
打开地图应用程序似乎会触发地理修复不会对应用程序位置进行某种更新?
由于
答案 0 :(得分:3)
所以在对这里的文档和其他问题进行了一些挖掘之后,我发现我实际上并没有在应用程序中更新位置。 (当我打开它时,这就是谷歌地图所做的,因此触发了新的位置设置)
现在可以使用此实现(当应用程序位于前台时):
protected GoogleApiClient googleApiClient;
protected LocationRequest locationRequest;
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
然后在重写的onConnected方法中:
@Override
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest, this);
}
此外,还需要onLocationChanged方法,因为该类现在正在实现LocationListener
@Override
public void onLocationChanged(Location location) {
//Whatever is required when the location changes
}