xamarin for android在尝试请求位置更新时抛出NullReferenceException

wnrlj8wa  于 2022-12-07  发布在  Android
关注(0)|答案(1)|浏览(126)

I can't seem to figure out, why is this causing an exception.

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

Calling IsProviderEnabled for the "gps" provider returns true .
GetSystemService does also return a valid LocationManager and not a null. gps object is also not null. ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION are also added to the manifest.
The call stack

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)

The internal exception message is "Object reference not set to an instance of an object."
How can i find out more information what is actually not set in this situation. And how could i fix it. The error happens both in emulator (API 30) and physical phone with Android 7.

t5fffqht

t5fffqht1#

请确保您的应用已被用户授予有关位置的权限,而不仅仅是在AndroidManifest.xml中声明它。您可以将以下代码添加到Activity的oncreate方法中来实现这一点。

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

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

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

相关问题