如何在Android中使用下载管理器在SD卡上保存文件?

时间:2013-04-30 07:10:00

标签: android

我在我的应用中面临两个问题。

1-我使用Android DownloadManager下载在线文件,但是使用

将所有文件下载到系统目录Download目录
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, "fileName");

现在我想将文件下载到我自己的目录中说“新建文件夹”。如何实施呢?请在这方面帮助我,我会非常感激。

2-如何检查SD卡是否可用?

2 个答案:

答案 0 :(得分:7)

使用这种方式:这里Dhaval_files是我的文件夹名称

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

    }

答案 1 :(得分:3)

DownloadManager

1)

Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
            DownloadManager.Request request = new DownloadManager.Request(downloadUri);
            request.setDescription("Downloading a file");
            long id =  downloadManager.enqueue(request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE)
                    .setAllowedOverRoaming(false)
                    .setTitle("File Downloading...")
                    .setDescription("Image File Download")
                    .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "cm.png"));

2)

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

if(isSDPresent)
{
  // yes download code
}
else
{
 // No sdcard 
}