设置自定义文件夹Android下载管理器

27

我有关于下载管理器的问题。 我要从一个网站下载一个文件。当我设置默认下载目录(Environment.DIRECTORY_DOWNLOAD)时,一切正常,我的下载也开始了。但是如果我试图更改目录,我的应用程序就无法下载该文件。特别是,我希望我的文件进入Download文件夹内的一个文件夹,例如 /storage/sdcard/Download/myFolder。我该如何解决这个问题?

File mydownload = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/myFolder");

if (!mydownload.exists()){
    mydownload.mkdir();
}

String url = sUrl[0];
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}

request.setDestinationInExternalPublicDir(mydownload.getAbsolutePath(),"Myfile.extension");


DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
4个回答

94

请检查下面的代码:它将文件保存在"sdcard/dhaval_files/"。只需替换您的文件夹名称并在Android清单文件中授予write_external_storage权限。

public void file_download(String uRl) {
        File direct = new File(Environment.getExternalStorageDirectory()
                + "/dhaval_files");

        if (!direct.exists()) {
            direct.mkdirs();
        }

        DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);

        Uri downloadUri = Uri.parse(uRl);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);

        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("Demo")
                .setDescription("Something useful. No, really.")
                .setDestinationInExternalPublicDir("/dhaval_files", "test.jpg");

        mgr.enqueue(request);

    }

非法状态异常,无法创建目录。 - Cyph3rCod3r
3
@Dr.aNdRO: 这是您的答案:https://dev59.com/iGQn5IYBdhLWcg3wETzj#17112536 和 https://dev59.com/lWrWa4cB1Zd3GeqP6QWg#13056375。 - Dhaval Parmar
这对我来说非常有帮助,我向您的努力致敬。 - Najaf Ali
@DhavalParmar的回答有点令人困惑,因为我尝试将其作为接受的答案,但是出现了“Illegalstate exeception unable to create directory”错误。这是因为要创建目录,用户需要给予运行时权限。要获取运行时权限,您可以参考此帖子[https://dev59.com/J1wX5IYBdhLWcg3w-Thv]。 - Saddan
无论谁使用这段代码,请确保在用户卸载您的应用程序时删除文件。 - Bhavik Mehta

14

您有两个选项可供使用。

1)首先使用setDestinationInExternalPublicDir,这将允许您根据媒体类型在Android标准下载文件夹中的任何一个进行下载,例如DIRECTORY_DOWNLOADS、DIRECTORY_MUSIC。这些文件将在卸载后保留。

request.setDestinationInExternalPublicDir(DIRECTORY_DOWNLOADS,
        File.separator + folderName + File.separator + fileName);

为了使其正常工作,第一个参数应该是一个标准的下载目录,不能是其他任何东西。

2) 第二个参数是setDestinationInExternalFilesDir, 与前一种方法相同,不同之处在于这些文件将在卸载应用程序后被删除。

request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS, 
        File.separator + folderName + File.separator + fileName);

这里的第二个参数可以为null或任何Android下载目录。


1

尝试以下代码:

    String storagePath = Environment.getExternalStorageDirectory()
                        .getPath()
                        + "/Directory_name/";
                //Log.d("Strorgae in view",""+storagePath);
                File f = new File(storagePath);
                if (!f.exists()) {
                    f.mkdirs();
                }
                //storagePath.mkdirs();
                String pathname = f.toString();
                if (!f.exists()) {
                    f.mkdirs();
                }
//                Log.d("Storage ",""+pathname);
                dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                Uri uri = Uri.parse(image);
                checkImage(uri.getLastPathSegment());
                if (!downloaded) {
                    DownloadManager.Request request = new DownloadManager.Request(uri);
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                    request.setDestinationInExternalPublicDir("/Directory_name", uri.getLastPathSegment());
                    Long referese = dm.enqueue(request);

                    Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_SHORT).show();
                }

0

设置下载文件路径的方法:适用于我(Android 11)。

 File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");

        request.setDestinationUri(Uri.fromFile(file));

完整代码:

首先检查目录

  private boolean CreateDirectory() {
    boolean ret = false;
    File filepath = Environment.getExternalStorageDirectory();
    File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
    if (!dir.exists()) {
        try {
            dir.mkdirs();
            ret = true;

        } catch (Exception e) {
            ret = false;
            e.printStackTrace();
        }
    }
    return ret;
}

然后:

        String URL = " YOUR URL ";

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setTitle("YOUR TITLE");
        request.setDescription("YOUR DESCRIPTION");
        request.allowScanningByMediaScanner();
   request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");

        request.setDestinationUri(Uri.fromFile(file));
        DownloadManager manager= (DownloadManager) 
        getSystemService(Context.DOWNLOAD_SERVICE);
        Long downloadId= manager.enqueue(request);

好的,完成


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接