[英]How to make a downloaded file visible in File Manager after written/downloaded into Android?
我已經成功從服務器下載文件並保存在Android存儲中,但是文件存儲在一個深路徑中,例如: /storage/emulated/0/Android/data/example.com.yourapp/files/Download/example_file.pdf
我目前使用的代碼是這樣的:
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
File filesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
assert filesDir != null;
downloadedFile = new File(filesDir,
"file_name" + ".pdf");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(downloadedFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
Functions.scanFile(getContext(), downloadedFile, "application/pdf");
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
我想要的是,當下載過程成功並打開文件管理器時,可以在之前的最新文件中看到已經下載的最新文件。
我還不知道,但我想我需要使用 MediaStore 通過嘗試以下代碼使我的文件在文件管理器中可見:
public static void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection.scanFile(ctxt, new String[] {f.getAbsolutePath()}, new String[] {mimeType}, null);
}
但它也沒有奏效。 我如何實現這一目標?
所以我只是改變File filesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
進入File filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
它在文件管理器的最近文件中可用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.