当我调用方法CheckSelfPermission(权限)时,我得到异常Java.Lang.NullPointerException(尝试调用虚方法' int android.content.Context.checkSelfPermission(java.lang.String)' on一个空对象引用)。 为什么? 请帮帮我
public void GetLocationPermission()
{
string permission = Manifest.Permission.AccessFineLocation;
if (CheckSelfPermission(permission) == (int)Permission.Granted)
{
GetLocation();
return;
}
RequestPermissions(PermissionsLocation, RequestLocationId);
}
readonly string[] PermissionsLocation =
{
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation
};
const int RequestLocationId = 0;
答案 0 :(得分:1)
根据我的经验,在这种情况下NullPointerException是由于Activity
设置不正确。
确保扩展Activity
并按以下方式添加属性:
[Activity(Label = "MyClass")]
class MyClass: Activity`
此外,使用Xamarin.Essentials 1.4.0时,请求权限变得更加容易。
您现在要做什么:
[Activity(Label = "MyClass")]
class MyClass: Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Platform.Init(this, savedInstanceState);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
public async Task<PermissionStatus> CheckAndRequestLocationPermission()
{
var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
if (status != PermissionStatus.Granted)
{
status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
}
// Additionally could prompt the user to turn on in settings
return status;
}
}
您还需要确保您的MainActivity
具有与OnRequestPermissionsResult
相同的覆盖,如果您没有手动创建项目,则默认情况下应该具有该覆盖。