android拍照、相册选取的方法,权限获取用的RxPermissions。
拍照
private Uri outputFileUri; //返回文件uri
public void camera() {
if (SdkVersionUtils.hasMarshmallow()) { //6.0
rxPermissions
.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE) //相机、外部存储卡权限
.subscribe(granted -> {
if (granted) { // Always true pre-M
if (SdkVersionUtils.hasN()) { //7.0 获取uri
mFile = FileUtils.createImageFile();
ContentValues contentValues = new ContentValues(1);
contentValues.put(MediaStore.Images.Media.DATA, mFile.getAbsolutePath());
outputFileUri = getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
} else {
mFile = FileUtils.createImageFile();
outputFileUri = Uri.fromFile(mFile);
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent, Constant.TAKE_PHOTO);
}
} else if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
ToastUtils.showShortToast(getContext(),"已拒绝权限");
FileUtils.deleteFile(mFile);
} else {
ToastUtils.showShortToast(getContext(),"获取权限失败,需去系统设置中打开");
FileUtils.deleteFile(mFile);
}
});
} else {
mFile = FileUtils.createImageFile();
outputFileUri = Uri.fromFile(mFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(intent, Constant.TAKE_PHOTO);
}
}
}
相册
public void album() {
if (SdkVersionUtils.hasMarshmallow()) {
rxPermissions
.request(Manifest.permission.READ_EXTERNAL_STORAGE)
.subscribe(granted -> {
if (granted) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, Constant.IMPORT_IMG);
} else if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
ToastUtils.showShortToast(mContext, "已拒绝读取外部存储卡权限");
} else {
ToastUtils.showShortToast(mContext, "获取外部存储卡权限失败,需去系统设置中打开");
}
});
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, Constant.IMPORT_IMG);
}
}
网友评论