问题描述: 在安卓模拟器中,通过代码获取默认位置信息时,位置不显示。
解决方法:
private static final int REQUEST_LOCATION_PERMISSION = 1;
// 请求位置权限
private void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
// 如果之前拒绝过权限请求,这里可以给出解释或提示
}
else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
}, REQUEST_LOCATION_PERMISSION);
}
}
// 处理权限请求结果
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限已授予,执行获取位置信息的操作
// ...
}
else {
// 权限被拒绝,可以给出提示或进行其他处理
}
}
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 没有位置权限,需要先请求权限
requestLocationPermission();
return;
}
// 获取最后一次已知的位置信息
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// 处理位置信息
}
请注意,如果模拟器没有模拟位置信息,获取的位置信息可能为空。在真实设备上测试时,确保已经打开了模拟位置选项或者使用了真实的位置信息。