Xamarin。 Android权限。 CheckSelfPermission()异常Java.Lang.NullPointerException

时间:2017-09-14 10:46:31

标签: c# xamarin permissions xamarin.android

当我调用方法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;

1 个答案:

答案 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相同的覆盖,如果您没有手动创建项目,则默认情况下应该具有该覆盖。

进一步阅读:Xamarin.Essentials: Permissions