android - 下载的图像显示在 android studio 但不是画廊
问题描述
我正在尝试通过我创建的服务使用 url 下载图像,当我通过 Android Studio 调试器检查设备的文件目录时,我可以在设备中看到该文件:
红色文件是有问题的下载文件。绿色图像文件是我通过 Windows 资源管理器手动拖入目录的文件。
我可以在我的图库应用程序中成功查看并打开绿色文件,但找不到红色文件(以及该目录中列出的所有其他文件)。我也无法在 Windows 资源管理器中看到它们。我是否应该在我的代码中将它们标识为图像,以便文件系统知道它是图像?
这是我下载图像的部分:
Request.Builder builder = new Request.Builder();
builder = builder.url(downloadFileUrl);
builder = builder.addHeader("RANGE", "bytes=" + existLocalFileLength);
Request request = builder.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
if (response != null && response.isSuccessful()) {
RandomAccessFile downloadFile = new RandomAccessFile(existLocalFile, "rw");
downloadFile.seek(existLocalFileLength);
ResponseBody responseBody = response.body();
InputStream inputStream = responseBody.byteStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
byte data[] = new byte[102400];
long totalReadLength = 0;
int readLength = bufferedInputStream.read(data);
while (readLength != -1) {
if (getDownloadManager().isDownloadPaused()) {
ret = DOWNLOAD_PAUSED;
break;
} else if (getDownloadManager().isDownloadCanceled()) {
ret = DOWNLOAD_CANCELED;
break;
} else {
downloadFile.write(data, 0, readLength);
totalReadLength = totalReadLength + readLength;
int downloadProgress = (int)((totalReadLength + existLocalFileLength) * 100 / downloadFileLength);
getDownloadManager().updateTaskProgress(downloadProgress);
readLength = bufferedInputStream.read(data);
}
}
}
解决方案
您需要使用 MediaScannerConnection 扫描保存的文件:
private void scanFile(String path) {
MediaScannerConnection.scanFile(context,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.d("Tag", "Scan finished. You can view the image in the gallery now.");
}
});
}
在您的existLocalFile 路径上调用它:
scanFile(existLocalFile.getAbsolutePath());
推荐阅读
- flutter - 当 Navigator.push 在颤动中移动到另一个屏幕时如何调用 AlertDialog
- java - Java的新手试图弄清楚如果给定某个输入,如何在do-while循环中跳回
- wso2 - WSO2 IS 如何使用用户证书获取 oauth2 令牌
- javascript - 如何将 const 变量传递给事件处理程序
- ibm-datapower - dp:url-open 的超时值在 datapower 中被忽略
- bash - 如何在 SDKMAN 中使用本地 jdk!脚本
- angular - 如何对 Kendo DropDownButton 的项目进行分组(在它们之间添加水平线)
- dynamics-crm - 如何在 Power Apps 中将 json 转换为集合
- java - 即使使用 doReturn,Mockito 也会调用存根方法
- python - 如何将列表列表组合成字典,其中嵌套列表的第一个元素是键