Android 7.0(API 7.0)、Android 9.0和Android 10+可以正常工作,但在Android 8.1(API 27)上,我收到此错误(调试或发布模式):
Unable to get location: System.NullReferenceException: Object reference not set to an instance of an object
at Project.Permissions.GetCurrentPosition () [0x000a9] in <f8798290f683423180c09ee7a2b0a8fa>:0
我的代码的相关部分:
项目.权限类:
public class Permissions
{
public async Task<bool> LocationPermission()
{
try
{
PermissionStatus Location = await new Permissions.LocationWhenInUse().CheckStatusAsync();
if (Location == PermissionStatus.Granted)
return true;
else
{
PermissionStatus status = await new Permissions.LocationWhenInUse().RequestAsync();
if (status == PermissionStatus.Granted)
return true;
else
return false;
}
}
catch (Exception ex)
{
Console.WriteLine("Error =>" + ex.Message);
return false;
}
}
public async Task<Position> GetCurrentPosition()
{
Position position;
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Best);
Location locator = await Geolocation.GetLastKnownLocationAsync();
locator.Accuracy = 50;
Location localNow = await Geolocation.GetLocationAsync(request);
localNow.Accuracy = 50;
if (localNow?.Latitude != null && localNow?.Longitude!=null)
position = new Position(localNow.Latitude, localNow.Longitude);
else
position = new Position(locator.Latitude, locator.Longitude);
}
catch (FeatureNotSupportedException fnsEx)
{
position = new Position(0, 0);
// Handle not supported on device exception
Debug.WriteLine("Feature not supported => " +fnsEx);
}
catch (PermissionException pEx)
{
position = new Position(0, 0);
// Handle permission exception
Debug.WriteLine("Error => "+pEx);
}
catch (Exception ex)
{
position = new Position(0,0);
Console.WriteLine("Unable to get location => " + ex);
}
return position;
}
}
Android清单:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
主要活动:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
我做错了什么?
1条答案
按热度按时间bis0qfac1#
问题出在
Location locator = await Geolocation.GetLastKnownLocationAsync();
中它尝试获取最后一个已知位置,但由于模拟器设备是第一次执行,因此该位置不存在,因此它返回NULL并导致System.NullReferenceException。