简体   繁体   中英

Save PDF in Xamarin Forms when targeting Android 11

I want a method to save PDF that coming as a byte[] from the server. iOS working well. In Android, I need to save the PDF in my app specific storage location. Previously I saved in the common external storage location. With the new android policy I cannot do that. All my updates are rejected from the play store. Is there a way to use Xamarin.Essential for save the PDF? Can we use Directory.CreateDirectory in Android 11 now?

Code for saving the file..

   public class AndroidSaveFile : ISaveFile
    {
        public async Task<string> SaveFiles(string filename, byte[] bytes, string filePath)
        {
            var status = await CrossPermissions.Current.CheckPermissionStatusAsync<StoragePermission>();
            if (status != PermissionStatus.Granted)
            {
                if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
                {
                    await Application.Current.MainPage.DisplayAlert("Storage permission!", "To save files, you need the storage permissions.", "OK");
                }

                status = await CrossPermissions.Current.RequestPermissionAsync<StoragePermission>();
            }

            if (status == PermissionStatus.Granted)
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                File.WriteAllBytes(filename, bytes);
            }
            else if (status != PermissionStatus.Unknown)
            {
                await Application.Current.MainPage.DisplayAlert("Storage Denied!", "Can not access storage on this device. Please check the permission and try again.", "OK");
            }

            return filename;
        }
    }

According to the native docs, we could not create our own directory on external storage.

Starting in Android 11, apps cannot create their own app-specific directory on external storage. To access the directory that the system provides for your app, call getExternalFilesDirs().

For more details about, please check the Storage updates in Android 11:https://developer.android.com/about/versions/11/privacy/storage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM