Java.Lang.NullPointerException: '尝试调用虚方法'void android.app.Activity.requestPermissions(java.lang.String[], int)'

Java.Lang.NullPointerException: 'Attempt to invoke virtual method 'void android.app.Activity.requestPermissions(java.lang.String[], int)'

我试图在应用程序的 class 上请求 READ_CONTACTS 权限但抛出异常 例外 Java.Lang.NullPointerException: '尝试在空对象引用上调用虚拟方法 'void android.app.Activity.requestPermissions(java.lang.String[], int)''

{
    public App(SignalrMessenger signalrMessenger, ChatServicesSettings chatServicesSettings, ContactServices contactServices)
    {
        InitializeComponent();
        

        if (!IsPermissioGranted(Android.App.Application.Context, Manifest.Permission.ReadContacts))
        {
            RequestPermission(Android.App.Application.Context as Activity, new[] { Manifest.Permission.ReadContacts }).GetAwaiter().GetResult();
        }

        MauiApplicationServices.WasDatabaseUpdatedOnStartUp = contactServices.SynchronizeDbWithLocalContacts().GetAwaiter().GetResult();

        MainPage = new MainPage(signalrMessenger,chatServicesSettings);//new AppShell();
    }
    public bool IsPermissioGranted(Context ctx, string permission)
    {
        return ActivityCompat.CheckSelfPermission(ctx, permission)== Permission.Granted;
    }
    public async Task RequestPermission(Activity activity, params string[] permissions)
    {
        ActivityCompat.RequestPermissions(activity, permissions, 0);
        await Task.CompletedTask;
    }
}

所以我想知道是否有可能在 Activity 中请求许可并注入服务 OnCreate 方法?因为在 MainActity 应用程序初始化中调用了默认 ctor

OnCreate 方法将按预期在 MainActivity class.

中触发

您可以在 MainActivity 中请求权限,而不是 App class。

示例代码

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == (int)Permission.Granted)
        {
            // We have permission, go ahead and use the camera.
        }
        else
        {
            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Camera },0);
        }
    }

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
    {
         base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }