如何将应用程序生成的文件存储在Android的“下载”文件夹中?

bjg7j2ky  于 2022-12-09  发布在  Android
关注(0)|答案(8)|浏览(281)

我正在我的应用程序中生成一个excel表,生成后应自动保存在任何Android设备的**“Downloads”**文件夹中,所有下载通常保存在该文件夹中。
我有以下保存文件在“我的文件”文件夹-

File file = new File(context.getExternalFilesDir(null), fileName);

导致-

W/FileUtils﹕ Writing file/storage/emulated/0/Android/data/com.mobileapp/files/temp.xls

我更希望在生成Excel工作表时将生成的文件自动保存在**“Downloads”**文件夹中。

**更新#1:**请在此处查看快照。我想要的是红色圆圈中的文件夹,如果您认为有意义,您建议的内容将存储在蓝色圆圈中(/storage/emulated/0/download)。请建议我如何将文件保存在红色圆圈中,即“Downloads”文件夹,该文件夹不同于“MyFiles”下的/storage/emulated/0/Download

oxcyiej7

oxcyiej71#

使用此命令获取目录:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

不要忘记在manifest.xml中设置此权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
rpppsulh

rpppsulh2#

现在从你的问题编辑我想更好地理解你想要什么。文件显示在下载菜单上从一个红色圆圈是那些实际上是通过DownloadManager下载的,虽然我给你的previos步骤将保存文件在您的下载文件夹,但他们不会显示在这个菜单上,因为他们没有下载。然而,使这一工作,您必须启动文件下载,以便在此处显示文件。
以下是如何开始下载的示例:

DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // to notify when download is complete
request.allowScanningByMediaScanner();// if you want to be available from media players
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
manager.enqueue(request);

此方法用于从URI下载,我还没有将其用于本地文件。
如果您的文件不是来自互联网,您可以尝试保存一个临时副本,并为此值获取文件的URI。

6gpjuf90

6gpjuf903#

只需使用DownloadManager下载生成的文件,如下所示:

File dir = new File("//sdcard//Download//");

File file = new File(dir, fileName);

DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);

downloadManager.addCompletedDownload(file.getName(), file.getName(), true, "text/plain",file.getAbsolutePath(),file.length(),true);

"text/plain"是你传递的mime类型,所以它会知道哪些应用程序可以运行下载的文件。

yuvru6vn

yuvru6vn4#

我使用以下代码在我的Xamarin Droid项目中使用C#实现了这一点:

// Suppose this is your local file
var file = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
var fileName = "myFile.pdf";

// Determine where to save your file
var downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, fileName);

// Create and save your file to the Android device
var streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, file);

// Notify the user about the completed "download"
var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);
downloadManager.AddCompletedDownload(fileName, "myDescription", true, "application/pdf", filePath, File.ReadAllBytes(filePath).Length, true);

现在,您的本地文件被“下载”到您的Android设备上,用户会收到一个通知,并且一个对该文件的引用被添加到下载文件夹中。不过,请确保在写入文件系统之前向用户请求权限,否则将抛出“访问被拒绝”异常。

rkkpypqq

rkkpypqq5#

适用于API 29及以上

根据documentation,要求使用Storage Access Framework作为Other types of shareable content, including downloaded files
应使用系统文件选取器将文件保存到外部存储目录。
将文件复制到外部存储示例:

// use system file picker Intent to select destination directory
private fun selectExternalStorageFolder(fileName: String) {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"
        putExtra(Intent.EXTRA_TITLE, name)
    }
    startActivityForResult(intent, FILE_PICKER_REQUEST)
}

// receive Uri for selected directory
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        FILE_PICKER_REQUEST -> data?.data?.let { destinationUri ->
            copyFileToExternalStorage(destinationUri)
        }
    }
}

// use ContentResolver to write file by Uri
private fun copyFileToExternalStorage(destination: Uri) {
    val yourFile: File = ...

    try {
        val outputStream = contentResolver.openOutputStream(destination) ?: return
        outputStream.write(yourFile.readBytes())
        outputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}
kr98yfug

kr98yfug6#

由于Oluwatumbi已正确回答了此问题,但首先需要检查是否通过以下代码为WRITE_EXTERNAL_STORAGE授予了权限:

int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission is not granted
        // Request for permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

    }else{
        Uri uri = Uri.parse(yourUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // to notify when download is complete
        request.allowScanningByMediaScanner();// if you want to be available from media players
        DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        manager.enqueue(request);
    }
bnl4lu3b

bnl4lu3b7#

这是使用Xamarin android API版本29的DownloadManager运行代码下载文件

public bool DownloadFileByDownloadManager(string imageURL)
        {
            try
            {
                string file_ext = Path.GetExtension(imageURL);
                string file_name = "MyschoolAttachment_" + DateTime.Now.ToString("yyyy MM dd hh mm ss").Replace(" ", "") + file_ext;
                var path = global::Android.OS.Environment.DirectoryDownloads;

                Android.Net.Uri uri = Android.Net.Uri.Parse(imageURL);
                DownloadManager.Request request = new DownloadManager.Request(uri);
                request.SetDestinationInExternalPublicDir(path, file_name);
                request.SetTitle(file_name);
                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted); // to notify when download is complete

                // Notify the user about the completed "download"
                var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);

                var d_id = downloadManager.Enqueue(request);
                return true;
            }
            catch (Exception ex)
            {
                UserDialogs.Instance.Alert("Error in download attachment.", "Error", "OK");
                System.Diagnostics.Debug.WriteLine("Error !" + ex.ToString());
                return false;
            }
        }
abithluo

abithluo8#

在API 29和30上工作

要获取目录,请执行以下操作:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

在您的AndroidManifest.xml中设置此权限:

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

将requestLegacyExternalStorage添加到AndroidManifest.xml中的应用程序标记(适用于API 29):

<application
    ...
    android:requestLegacyExternalStorage="true">

相关问题