Search code examples
c#androidmaui

Using Manage_External_Storage with .net Maui


So i am Creating an android app with .net Maui, that reads an XML file from my Documents(/storage/emulated/0/Documents) folder. The App is 100% capable of generating its own XML file to ensure that it always exists. However if i Replace the XML the Application crashes with an access denied execption. I believe this is due to the Fact that i am Using Storage_Read and Storage_Write Permissions instead of Manage_External_Storage. I am now Looking for a workaround to geting that permission since .net maui has not yet updated its permission system to API level 34.

The code That Requests Permissions:

PermissionStatus lReadStatus = await Permissions.RequestAsync<Permissions.StorageRead>();  
PermissionStatus lWriteStatus =await Permissions.RequestAsync<Permissions.StorageWrite>();

My Android Manifest.xml:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

Solution

  • To check external storage permission, you can use native android code. Here is a simple example.

    in Platforms -> Android add CheckPermissions.cs file

    namespace CheckPermissionManager
    {
        public static class CheckPermission
        {
            public static bool CheckExternalStoragePermission()
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.R)
                {
                    var result = Android.OS.Environment.IsExternalStorageManager;
                    if (!result)
                    {
                        var manage = Settings.ActionManageAppAllFilesAccessPermission;
                        Intent intent = new Intent(manage);
                        Android.Net.Uri uri = Android.Net.Uri.Parse("package:" + AppInfo.Current.PackageName);
                        intent.SetData(uri);
                        Platform.CurrentActivity.StartActivity(intent);
                    }
                    return result;
                }
    
                return true;
            }
        }
    }
    

    then anywhere in code:

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    
        private async void OnClicked(object sender, EventArgs e)
        {
    #if ANDROID
            CheckPermissionManager.CheckPermission.CheckExternalStoragePermission();
    #endif
        }
    }
    

    Permission can only be manually added from app setting page. Above code opens manage external permission page if these permissions are not added.

    Changing it to service would probably be a good idea.