【发布时间】:2016-11-16 10:35:49
【问题描述】:
我正在开发一个安卓应用,我想在应用启动后立即检索用户的当前位置。
我正在使用此代码:
@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,当未检测到位置并有一个“重试”按钮时会弹出。按下那个“RETRY”按钮后,上面的代码会再次执行,这次会检索到位置。
我想要的是,我想在应用启动后立即检索位置。
请告诉我。
【问题讨论】:
-
像往常一样回答...因为 getLastLocation 可能返回 null...
-
@Selvin 为什么每次启动应用程序都返回 null 而不是第二次尝试?
-
这可能是设备获取某个位置并设置为最后一个已知位置的时间。
-
@DiegoMalone 如何在应用启动时避免这种行为并检索位置?
-
@HammadNasir 我已经回答了问题,请看答案。
标签: android location android-location locationmanager location-services