//下载到本地私有目录的代码省略
if (file.getAbsolutePath().contains("MP4")) {
copyFileToGallery(file, file.getName());
} else {
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), BitmapFactory.decodeFile(file.getAbsolutePath()), file.getName(), null);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri11 = Uri.fromFile(file);
intent.setData(uri11);
getActivity().sendBroadcast(intent);
}
private void copyFileToGallery(File file, String fileName) {
Uri uriSavedVideo;
ContentResolver resolver = getActivity().getContentResolver();
ContentValues valuesVideos;
valuesVideos = new ContentValues();
if (Build.VERSION.SDK_INT >= 29) {
valuesVideos.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/" + "kacam");
valuesVideos.put(MediaStore.Video.Media.TITLE, fileName);
valuesVideos.put(MediaStore.Video.Media.DISPLAY_NAME, fileName);
valuesVideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesVideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
valuesVideos.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
valuesVideos.put(MediaStore.Video.Media.IS_PENDING, 1);
Uri collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
uriSavedVideo = resolver.insert(collection, valuesVideos);
} else {
valuesVideos.put(MediaStore.Video.Media.TITLE, fileName);
valuesVideos.put(MediaStore.Video.Media.DISPLAY_NAME, fileName);
valuesVideos.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
valuesVideos.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
//valuesVideos.put(MediaStore.Video.Media.DATA, file.getAbsolutePath());
uriSavedVideo = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, valuesVideos);
}
ParcelFileDescriptor pfd;
try {
pfd = resolver.openFileDescriptor(uriSavedVideo, "w");
FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
pfd.close();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 29) {
valuesVideos.clear();
valuesVideos.put(MediaStore.Video.Media.IS_PENDING, 0);
resolver.update(uriSavedVideo, valuesVideos, null, null);
}
}
Android 下载到APP私有目录的图片和视频同步到手机图库相册
最新推荐文章于 2024-04-25 15:24:22 发布