android拍照、相冊選取的方法询吴,權(quán)限獲取用的RxPermissions掠河。
拍照
private Uri outputFileUri; //返回文件uri
public void camera() {
if (SdkVersionUtils.hasMarshmallow()) { //6.0
rxPermissions
.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE) //相機亮元、外部存儲卡權(quán)限
.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(),"已拒絕權(quán)限");
FileUtils.deleteFile(mFile);
} else {
ToastUtils.showShortToast(getContext(),"獲取權(quán)限失敗猛计,需去系統(tǒng)設(shè)置中打開");
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, "已拒絕讀取外部存儲卡權(quán)限");
} else {
ToastUtils.showShortToast(mContext, "獲取外部存儲卡權(quán)限失敗,需去系統(tǒng)設(shè)置中打開");
}
});
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, Constant.IMPORT_IMG);
}
}