gpt4 book ai didi

android - Xamarin.Forms - 如何为 android 定义范围存储以及如何实现它以在 Downloads 目录中下载文件?

转载 作者:行者123 更新时间:2023-12-04 02:27:18 26 4
gpt4 key购买 nike

在我的应用程序中,我提供了以 PDF 格式下载报告的功能。一切都很好,直到我在 Android 10 及更低版本上测试我的应用程序。最近我将设备更新到 Android 11,现在我无法在共享存储中下载任何文件。我收到 Access Denied下载文件时出错。
我已授予读取和写入外部存储的权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我的下载路径是
Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
我也设置了 android:requestLegacyExternalStorage="true"AndroidManifest.xml我下载文件的代码如下所示
public async void DownloadSupplierSample(object sender, EventArgs e)
{
try
{
string basepath;
if (Device.RuntimePlatform == Device.Android)
basepath = DependencyService.Get<IDownloadPath>().GetDownloadsPath();
else
basepath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "..", "Library");

PermissionStatus readstatus = await Permissions.CheckStatusAsync<Permissions.StorageRead>();
PermissionStatus writestatus = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();

if (readstatus == PermissionStatus.Granted && writestatus == PermissionStatus.Granted)
{
DownloadSupplier(basepath);
}
else
{
var read = await Permissions.RequestAsync<Permissions.StorageRead>();
var write = await Permissions.RequestAsync<Permissions.StorageWrite>();

if (read == PermissionStatus.Granted && write == PermissionStatus.Granted)
{
DownloadSupplier(basepath);
}
}
await DisplayAlert("", "Sample is downaloaded at Downloads directory","Ok");
}
catch (Exception ex)
{
}
}

async void DownloadSupplier(string basepath)
{
using (var stream = await FileSystem.OpenAppPackageFileAsync("SupplierMaster.xlsx"))
{
string filename = $"SupplierMaster_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
string filepath = Path.Combine(basepath, filename);

byte[] bytes = Utils.Common.StreamToBytes(stream);
File.WriteAllBytes(filepath, bytes);
//using (Stream filestream = File.Create(filepath))
//{
// //stream.Seek(0, SeekOrigin.Begin);
// stream.CopyTo(filestream);
//}
}
}
我也试过从设备设置标志 link
如何为我的应用程序定义范围存储?
任何更新如何在我的下载目录中下载 PDF 文件?
谢谢你。

最佳答案

几个月前我遇到了同样的问题。
我在 developer.android 页面上找到了这个:
enter image description here
(https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory())
第一个替代方法 (getExternalFilesDir) 不会按您的意愿工作,文件不会出现在下载目录中,此位置在应用程序内部。
第二种选择是媒体文件。
我最终使用了第三种选择。我在 Android 项目中创建了一个服务类,如下所示:

public class FilesManager : IFilesManager
{
private const int CREATE_FILE_REQUEST_CODE = 123;
private static Context _context;

public static void Init(Context context)
{
_context = context;
}

public async Task SaveFile(string fileName, byte[] content)
{
Intent intent = new Intent(Intent.ActionCreateDocument);
intent.AddCategory(Intent.CategoryOpenable);
intent.SetType(your_file_mimeType);
intent.PutExtra(Intent.ExtraTitle, fileName);

var activity = (MainActivity)_context;
var listener = new ActivityResultListener(activity);
activity.StartActivityForResult(intent, CREATE_FILE_REQUEST_CODE);

var result = await listener.Task;

if (result == null)
{
// Cancelled by user
return;
}

using (Stream os = _context.ContentResolver.OpenOutputStream(result.Data))
{
os?.Write(content);
os?.Close();
}
}

private class ActivityResultListener
{
private readonly TaskCompletionSource<Intent> Complete = new TaskCompletionSource<Intent>();
public Task<Intent> Task { get { return this.Complete.Task; } }

public ActivityResultListener(MainActivity activity)
{
// subscribe to activity results
activity.ActivityResult += OnActivityResult;
}

private void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if(requestCode != CREATE_FILE_REQUEST_CODE)
{
return;
}

// unsubscribe from activity results
var activity = (MainActivity)_context;
activity.ActivityResult -= OnActivityResult;

// process result
if (resultCode == Result.Ok)
{
Complete.TrySetResult(data);
}
else
{
Complete.TrySetResult(null);
}
}
}
}
在 MainActivity.cs 添加:
public event Action<int, Result, Intent> ActivityResult;

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
ActivityResult?.Invoke(requestCode, resultCode, data);
}
您可以在 Forms.Init 之后调用 Init 方法:
FilesManager.Init(this);
注:此方法需要用户交互。系统将提示用户选择保存文件的位置。

关于android - Xamarin.Forms - 如何为 android 定义范围存储以及如何实现它以在 Downloads 目录中下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66560359/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com