我需要獲取當前設備位置(緯度/經度),但「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