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

时间:2015-01-28 03:01:44

标签: android

我正在我的应用中生成一个excelsheet,生成时应该自动保存在任何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工作表时自动将生成的文件保存在“下载”文件夹中。

更新#1:请在此处查看快照。我想要的是用红色圈出的那个,如果有意义,你建议的内容将被存储在一个带圆圈的蓝色(/ storage / emulated / 0 / download)中。请告知我如何将文件保存在一个带圆圈的红色文件夹中,即“下载”文件夹与/ storage / emulated / 0 /下的“MyFiles”下的文件不同

snapshot

7 个答案:

答案 0 :(得分:27)

使用此命令获取目录:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

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

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

答案 1 :(得分:13)

现在从你的问题编辑我想更好地理解你想要的东西。 下载菜单上显示的红色圆圈中的文件实际上是通过DownloadManager下载的文件,虽然我给你的普遍步骤会将文件保存在你的下载文件夹中,但它们不会显示在这个菜单中,因为它们是没下载。但是,要使其工作,您必须开始下载文件,以便在此处显示。

以下是如何开始下载的示例:

 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。

答案 2 :(得分:9)

只需使用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类型,因此它将知道哪些应用程序可以运行下载的文件。这样做对我来说。

答案 3 :(得分:4)

我使用以下代码在C#中使用Xamarin Droid项目:

// 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设备,用户会收到通知,并且该文件的引用将添加到下载文件夹中。但是,请确保在写入文件系统之前要求用户许可,否则将抛出“拒绝访问”异常。

答案 4 :(得分:1)

由于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);
    }

答案 5 :(得分:1)

对于 API 29 及更高版本

根据documentationStorage Access Framework需要使用Other types of shareable content, including downloaded files

System file picker 应该用于将文件保存到外部存储目录。

将文件复制到外部存储示例:

// 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()
    }
}

答案 6 :(得分:0)

这是使用DownloadManager for Xamarin android api 29版运行代码下载文件

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