android - Android:下载管理器请求缓存目录
问题描述
我需要使用本机下载管理器将敏感文件保存到缓存目录。用户无法发现的位置。我可以使用DownloadManager.Request()
. 尽管使用setDestinationInExternalPublicDir()
或任何其他方式设置目标,但不允许我保存到缓存目录。我在这里错过了什么吗?
解决方案
您必须忘记下载管理器中的 Android 构建并创建自己的管理器。然后你可以下载到路径:getCacheDir().getAbsolutePath();
这是一个示例代码,可以在没有内置管理器的情况下自己下载文件
public String downloadFile(String fileURL, String fileName) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.d(TAG, "Downloading...");
try {
int lastDotPosition = fileName.lastIndexOf('/');
if( lastDotPosition > 0 ) {
String folder = fileName.substring(0, lastDotPosition);
File fDir = new File(folder);
fDir.mkdirs();
}
//Log.i(TAG, "URL: " + fileURL);
//Log.i(TAG, "File: " + fileName);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(30000);
c.connect();
double fileSize = (double) c.getContentLength();
int counter = 0;
while ( (fileSize == -1) && (counter <=30)){
c.disconnect();
u = new URL(fileURL);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setReadTimeout(30000);
c.connect();
fileSize = (double) c.getContentLength();
counter++;
}
File fOutput = new File(fileName);
if (fOutput.exists())
fOutput.delete();
BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(fOutput));
InputStream in = c.getInputStream();
byte[] buffer = new byte[8192];
int len1 = 0;
int downloadedData = 0;
while ((len1 = in.read(buffer)) > 0) {
downloadedData += len1;
f.write(buffer, 0, len1);
}
Log.d(TAG, "Finished");
f.close();
return fileName;
}
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.toString());
return null;
}
}
推荐阅读
- java - 对 xml 模式中的值列表进行排序
- entity-framework-core - Automapper.ProjectTo() 抛出空引用异常
- git - git repack:按文件类型隔离和按组配置包?
- vcftools - 如何使用 vcftools 按读取深度进行过滤?
- mongodb - 无法连接robo 3t localhost;27017 窗户 10
- python - chrome 88 无法重新定义 webdriver
- sql - 我的 cs50 pset 7 10.sql 嵌套查询哪里出错了?
- c# - 在 DbContext 的 OnConfiguration 中使用 connectionString
- javascript - 事件的自定义视图
- html - 如何使用 css 在链接旁边添加文件格式图标