如何通过MAUI在Android上询问和允许存储权限的方法

问题描述 投票:0回答:1

我正在创建的 Android 应用程序需要访问 Android 手机公共存储位置上的某些文件。我知道我需要修改 AndroidManifes.XML 并请求权限。我已通读 MAUI 文档并查看了权限页面。但是,我不确定如何实现该页面上的示例。在我的 MAUI Android 应用程序中,我需要使用他们提供的代码。我希望在启动应用程序时询问权限。谁能更详细地解释一下在哪里使用权限代码。

这是我的 MainPage.xaml.cs 代码。我知道这是用于位置许可的,但我只是将其用作测试。

`

using Microsoft.Maui.Controls.PlatformConfiguration;
using Syncfusion.XlsIO;
using System.Reflection;
using Microsoft.Maui.Storage;

namespace MauiApp3
{
    public partial class MainPage : ContentPage
    {
        int count = 0;

        public MainPage()
        {
           
            InitializeComponent();
        }

        public async Task<PermissionStatus> CheckAndRequestLocationPermission()
        {
            PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();

            if (status == PermissionStatus.Granted)
                return status;

            if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
            {
                // Prompt the user to turn on in settings
                // On iOS once a permission has been denied it may not be requested again from the application
                return status;
            }

            if (Permissions.ShouldShowRationale<Permissions.LocationWhenInUse>())
            {
                // Prompt the user with additional information as to why the permission is needed
            }

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

            return status;
        }

        private void OnCounterClicked(object sender, EventArgs e)
        {
            var result = Task.Run(async () => await CheckAndRequestLocationPermission());
            result.Wait();
            ExcelEngine excelEngine = new ExcelEngine();

            //Initialize IApplication
            Syncfusion.XlsIO.IApplication application = excelEngine.Excel;

            //Load the file into stream

            string rootPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).AbsolutePath;
            string backingFile = Path.Combine(rootPath, "Proof.xlsx");
            //Stream reader = new StreamReader(backingFile);

            var reader = new MemoryStream();

            FileStream inputStream = new FileStream(backingFile, FileMode.Open, FileAccess.Read);
            //Assembly executingAssembly = typeof(App).GetTypeInfo().Assembly;
            //Stream inputStream = executingAssembly.GetManifestResourceStream(backingFile);

            //Loads or open an existing workbook through Open method of IWorkbooks
            IWorkbook workbook = application.Workbooks.Open(inputStream, ExcelOpenType.Automatic);

            IWorksheet worksheet = workbook.Worksheets[0];

            //worksheet.Range["A3"].Text = "Mooi";
            //worksheet.Range["A4"].Text = "10";
            worksheet.Range["A5"].Text = "Brilliant";

            string savePath = Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments).ToString();
            string saveFile = Path.Combine(savePath, "Proof.xlsx");

            FileStream stream = new FileStream(saveFile, FileMode.Create, FileAccess.ReadWrite);
            workbook.SaveAs(stream);
            workbook.Close();
            excelEngine.Dispose();
        }
    }
}
c# android maui android-permissions syncfusion
1个回答
0
投票

首先,您可以阅读有关Maui App Lifecycle的官方文档。

我希望在申请时询问权限 推出

您可以将请求权限的代码放在App.cs的生命周期方法中。如:

   public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            MainPage = new MainPage();

            // ask permission here
        }

        protected override Window CreateWindow(IActivationState activationState)
        {
            Window window = base.CreateWindow(activationState);

            window.Created += (s, e) =>
            {
                // ask persmission here
            };

            return window;
        }
        
        protected override void OnStart()
        {
           // ask persmission here
        }
    }

我的 MAUI Android 应用程序中的具体位置需要使用他们提供的代码

对于android,您可以将代码放在

\Platforms\Android\MainActivity.cs
中。

    public class MainActivity : MauiAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // ask permission here
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.