相机拍照、下载、存储照片等,在别的Android版本里都能用,为啥在Android12里用不了?
针对👆的问题,其实也不能这么说,比如你的targetSdkVersion小于30,Android12 也不会不能用。下面看看不能用时的处理方法:
- 清单文件中设置provider
<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/provider_paths" />
</provider>
其中的xml,provider_paths为
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="files_root"
path="Android/data/${applicationId}/"/>
<external-path
name="DCIM"
path="."/>
</paths>
- 调用
//用于保存调用相机拍照后所生成的文件
tempFile = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/", System.currentTimeMillis() + ".jpg");
//跳转到调用系统相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//判断版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //如果在Android7.0以上,使用FileProvider获取Uri
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(this, AppPFContants.getProviderName(), tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
Log.e("contentUri", contentUri.toString());
} else { //否则使用Uri.fromFile(file)方法获取Uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
}
其实走到这一步,应该跟你代码里一样,如果你的依旧像我之前一样不能用,那么你需要注意下,你的Environment.getExternalStorageDirectory().getPath() + "/DCIM/"
路径中文件夹的命名;
比如图片存储Environment.getExternalStorageDirectory().getPath() + "/DCIM/"
中的DCIM必须是DCIM
app下载则是Download
就是说高版本现在不允许,私自命名文件夹名字了,其他的自己找一找吧