适用于 Android 的 xamarin 在尝试请求位置更新时会抛出 NullReferenceException



我似乎想不通,为什么这会导致异常。

GPSListener gps = new GPSListener(); // <- implements ILocationListener interface
(LocationManager)GetSystemService(LocationService).RequestLocationUpdates(LocationManager.GpsProvider, 0, 0, gps); // <- System.NullReferenceException

调用"gps"提供程序的IsProviderEnabled将返回true

GetSystemService还会返回有效的位置管理器,而不是 null。gps对象也不是 null。ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION也会添加到清单中。

调用堆栈

at Android.Runtime.JNINativeWrapper._unhandled_exception (System.Exception e) [0x0000e] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:12
at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V (_JniMarshal_PP_V callback, System.IntPtr jnienv, System.IntPtr klazz) [0x0001c] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:23
at (wrapper native-to-managed) Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PP_V(intptr,intptr)

内部异常消息"Object reference not set to an instance of an object."

在这种情况下,我如何找到更多信息实际上没有设置的内容。我怎么能解决它。该错误在模拟器 (API 30) 和装有 Android 7 的物理手机中均发生。

请确保您的应用已被用户授予有关位置的权限,而不仅仅是在 AndroidManifest .xml中声明它。您可以将以下代码添加到活动的 oncreate 方法中以执行此操作。

var status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();

此外,如果在后台服务中调用该方法,则需要在 AndroidManifest.xaml 中添加ACCESS_BACKGROUND_LOCATION并使用以下代码:

var status = await Permissions.RequestAsync<Permissions.LocationAlways>();

最新更新