我在Xamarin.Android中遇到了这个问题。
Location location = locationManager.GetLastKnownLocation(provider);
返回空值。我检查了代码,得知我刚刚请求了对ACCESS_COARSE_LOCATION的许可。我添加了代码以请求对ACCESS_FINE_LOCATION的许可,现在它没有返回null。这是我的代码:
void AskPermissions()
{
if (CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) != (int)Permission.Granted ||
CheckSelfPermission(Manifest.Permission.AccessFineLocation) != (int)Permission.Granted)
RequestPermissions(new string[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation }, 0);
else
GetLocation();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
if (CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) == (int)Permission.Granted &&
CheckSelfPermission(Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
GetLocation();
else
Log.Info(tag, "Permission not Granted: Please enter desired Location manually.");
}
void GetLocation()
{
locationManager = (LocationManager)GetSystemService(LocationService);
provider = locationManager.GetBestProvider(new Criteria(), false);
Location location = locationManager.GetLastKnownLocation(provider);
if (location != null)
Log.Info(tag, "Location Lat: " + location.Latitude + " Lon: " + location.Longitude);
else
Log.Info(tag, "Location is null");
}
万一来自Xamarin.Android(C#)的人会发现它很有用。对于Java或Android Studio中的代码将是类似withs一些小的语法更改,如GetLastKnownLocation()
将getLastKnownLocation()
在Java方法的名称以小写字母开始,而在C#方法名以大写字母开头。