Android 为什么getLastLocation()方法在应用程序第一次启动时不检索位置?
我正在开发一个android应用程序,我想在应用程序启动后立即检索用户的当前位置 我正在使用以下代码:Android 为什么getLastLocation()方法在应用程序第一次启动时不检索位置?,android,location,android-location,locationmanager,location-services,Android,Location,Android Location,Locationmanager,Location Services,我正在开发一个android应用程序,我想在应用程序启动后立即检索用户的当前位置 我正在使用以下代码: @Override public void onConnected(@Nullable Bundle bundle) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
currentLatDouble = mLastLocation.getLatitude();
currentLngDouble = mLastLocation.getLongitude();
}
}
我使用的是一个Snackbar
,当没有检测到位置时会弹出,并且有一个“重试”按钮。按下“重试”按钮后,将再次执行上述代码,这一次将检索位置
我想要的是,我想在应用程序启动后立即检索位置
请让我知道。如果没有最后一个已知位置,则
LocationServices.FusedLocationApi.getLastLocation
方法可能返回null
最好的用法是请求位置更新并在onLocationChanged
回调中处理响应,如下所示:
@Override
public void onConnected(Bundle connectionHint) {
...
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
而LocationListener
将处理接收到的位置
public class MainActivity extends ActionBarActivity implements LocationListener {
...
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
}
一定要检查一下房间。这也可能对您有所帮助。aswer与往常一样。。。因为getLastLocation可能返回null…@Selvin为什么每次启动应用程序时返回null,而不是在第二次尝试时返回null?这可能是设备获取某些位置并设置为最后已知位置的时间。@Diegomone我如何避免这种行为并在启动应用程序时检索位置?@HammadNasir我已经回答了问题问题,请看一下答案。我不知道为什么,但该位置在应用程序启动时未被检索,而在第二次尝试时被检索!这是因为当应用程序启动时,对最后一个位置的请求是在它可以获得位置修复之前发出的。在随后的尝试中,它有足够的时间进行修复。如果您将重试操作放在init之后,可能在第二次调用中,它仍然没有位置。最好的方法是请求一个位置,一旦设备得到一个位置,您就假设它是第一个已知的位置。