使用downloadManager和临时文件

时间:2019-12-01 17:52:39

标签: android webview mime-types

我希望使用已完成大部分代码的DownloadManager,我想将其保留为临时文件,但是,我不喜欢w

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

似乎是其他方法的代码,但是DownloadManager似乎很好,一旦下载,我将做一些监听程序,如果用户仍在应用程序上,则尝试打开它,否则他们可以单击它。

我不希望它永久存储,只是缓存直到它填满一定数量。

private long startDownload(String downloadPath, String fileName) {
    Uri uri = Uri.parse(downloadPath); // Path where you want to download file.
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.addRequestHeader(Constants.TOKEN_KEY, getToken(uri.toString()));
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);  // Tell on which network you want to download file.
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  // This will show notification on top when downloading the file.
    request.setTitle(fileName); // Title for notification.
    request.setDescription(getString(R.string.downloading) + " " + fileName);
    request.setVisibleInDownloadsUi(true);
    request.setDestinationInExternalPublicDir(getResources().getString(R.string.app_name), fileName);
    //request.setDestinationInExternalPublicDir(getDocumentDirectoryString(), fileName);
    DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    return downloadManager.enqueue(request);// enqueue puts the download request in the queue.
}

private String getDocumentDirectoryString(){
    if (Build.VERSION.SDK_INT >= 19) {
        return Environment.DIRECTORY_DOCUMENTS;
    } else {
        return Environment.getExternalStorageDirectory() + "/Documents";
    }
}

这是我用于setDestination的代码,所以我不确定如何将两者合并并工作。

0 个答案:

没有答案