1权限 和 动态申请
<!--文件读写权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--拍照权限-->
<uses-permission android:name="android.permission.CAMERA" />
2 app 属性添加
然后在 你的application 中加入 这个属性 :
android:requestLegacyExternalStorage="true"
3 mxl 设置
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.base.baselib.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
在res 中添加 xml包和 file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="." />
</paths>
4 代码配置
在你的 Application继承类中添加
private void initFileXml() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
}
5 代码实现
/**
* 打开相机
*/
private void openPhotograph() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 创建文件工具类 设置相机图片路径(用时间戳)
mImagePath = FileUtils.getImageFilePath();
//检查文件是否存在
FileUtils.checkOrCreateDirectory(mImagePath);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mImagePath)));
mActivity.startActivityForResult(intent, Photograph_code);
}
/**
* 打开相册
*/
private void openAlbum() {
//打开系统的相册
if (mMaxSize == 0) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
mActivity.startActivityForResult(intent, Album_code);
return;
}
//打开自定义的相册
AlbumActivity.gotoActivity(mActivity, AlbumList_code, mMaxSize);
}
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (mAlbumListener == null) return;
if (resultCode != RESULT_OK) return;
List<String> list = new ArrayList<>();
if (requestCode == AlbumList_code && data != null) {
//多选图片
list = (List<String>) data.getSerializableExtra(ImageList);
}
if (requestCode == Album_code && data != null) {
//单选图片 获图片的绝对地址
mImagePath = FileUtils.getImageAbsolutePath(mActivity, data.getData());
list.add(mImagePath);
}
if (requestCode == Photograph_code) {
//拍照图片
list.add(mImagePath);
}
mAlbumListener.onListener(list);
}