private void takePhoto() {
final String currentPhotoName = getPhotoName();
final Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final File tempFile =new File(FileUtil.CAMERA_PHOTO_DIR, currentPhotoName);
//兼容7.0及以上的写法
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final ContentValues contentValues =new ContentValues(1);
contentValues.put(MediaStore.Images.Media.DATA, tempFile.getPath());
final Uri uri =DELEGATE.getContext().getContentResolver().
insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//需要讲Uri路径转化为实际路径
final File realFile =
FileUtils.getFileByPath(FileUtil.getRealFilePath(DELEGATE.getContext(), uri));
final Uri realUri = Uri.fromFile(realFile);
CameraImageBean.getInstance().setPath(realUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}else {
final Uri fileUri = Uri.fromFile(tempFile);
CameraImageBean.getInstance().setPath(fileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
}
DELEGATE.startActivityForResult(intent, RequestCodes.TAKE_PHOTO);
}
private void pickPhoto() {
final Intent intent =new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
DELEGATE.startActivityForResult
(Intent.createChooser(intent,"选择获取图片的方式"), RequestCodes.PICK_PHOTO);
}
/**
* 获取文件得真实路径
*/
public static String getRealFilePath(final Context context,final Uri uri) {
if (null == uri)return null;
final String scheme = uri.getScheme();
String data =null;
if (scheme ==null)
data = uri.getPath();
else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
data = uri.getPath();
}else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
final Cursor cursor = context.getContentResolver().query(uri,new String[]{MediaStore.Images.ImageColumns.DATA},null,null,null);
if (null != cursor) {
if (cursor.moveToFirst()) {
final int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
if (index > -1) {
data = cursor.getString(index);
}
}
cursor.close();
}
}
return data;
}
/**
* 根据文件路径获取文件
*
* @param filePath 文件路径
* @return 文件
*/
public static File getFileByPath(String filePath) {
return isSpace(filePath) ?null :new File(filePath);
}