【问题标题】:Save PDF in Xamarin Forms when targeting Android 11面向 Android 11 时在 Xamarin 表单中保存 PDF
【发布时间】:2022-01-18 13:39:23
【问题描述】:

我想要一种方法来保存来自服务器的 byte[] 格式的 PDF。 iOS 运行良好。在 Android 中,我需要将 PDF 保存在我的应用程序特定的存储位置。以前我保存在通用的外部存储位置。使用新的 android 政策,我无法做到这一点。我的所有更新都被 Play 商店拒绝。有没有办法使用 Xamarin.Essential 来保存 PDF?我们现在可以在 Android 11 中使用 Directory.CreateDirectory 了吗?

保存文件的代码..

   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;
        }
    }

【问题讨论】:

    标签: android xamarin.forms


    【解决方案1】:

    根据本机文档,我们无法在外部存储上创建自己的目录。

    从 Android 11 开始,应用无法创建自己的应用专用 外部存储上的目录。访问系统的目录 为您的应用提供,请调用 getExternalFilesDirs()。

    更多详情请查看 Android 11 中的存储更新:https://developer.android.com/about/versions/11/privacy/storage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2019-04-22
      • 1970-01-01
      • 2022-01-19
      • 2017-05-24
      • 1970-01-01
      相关资源
      最近更新 更多