问题:拉起系统相机拍照并存储到公共区域,图片文件可见,系统相册中却看不到
实现:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File publicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String path = publicDir.getAbsolutePath() + "/Camera";
this.takePhotoFile = createImageFile(path);
if (VERSION.SDK_INT >= 24) {
String pkName = activity.getPackageName();
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(activity,pkName + ".fileProvider", takePhotoFile));
} else {
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(takePhotoFile));
}
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); // 授予临时写入权限
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivity(intent);
}
private File createImageFile(String photoAbsolutePath) throws IOException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timeStamp = format.format(new Date());
String imageFileName = timeStamp + ".jpg";
File image = new File(photoAbsolutePath, imageFileName);
return image;
}
//发送广播给系统,刷新数据库
Uri uri = Uri.fromFile(takePhotoFile);
Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
mContext.sendBroadcast(localIntent);
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
<root-path name="root_path" path="." />
<files-path name="files_path" path="." />
<cache-path name="cache-path" path="." />
</paths>
总结:
1.需要发送广播给系统,刷新数据库
2.照片存储使用FileProvider