我需要获取当前设备位置(纬度/经度),但“getCurrentLocation()”始终显示“无提供商”,因此位置为空。我把这种方法的onCreate(),并宣布在清单文件中的所有权限:无法获得当前位置
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
真实设备位置服务已启用为好。
getCurrentLocation()java代码:
public void getCurrentLocation() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
provider = locationManager.getBestProvider(c, false);
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;
}
location = locationManager.getLastKnownLocation(provider);
if(location!=null)
{
double lng=location.getLongitude();
double lat=location.getLatitude();
Toast.makeText(this, Double.toString(lat) + "\n" + Double.toString(lng), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "No provider", Toast.LENGTH_SHORT).show();
}
}
我怎样才能解决这个问题?
P.S .:我修改了很多类似的问题,但找不到合适的解决方案。
你已经评论了有关权限的部分,你是否至少给了使用设置的权限? (Android 5.0及更早版本) – AxelH