1.拍照 (对于7.0以上的版本,不在允许直接访问uri)
`
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(srcActivity));
if (Build.VERSION.SDK_INT > 22) {
List<ResolveInfo> resInfoList = srcActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
srcActivity.grantUriPermission(packageName, getTempUri(srcActivity), Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
srcActivity.startActivityForResult(intent, ACTION_CAPTURE);`
若不指定输出路径intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(srcActivity)); 在onActivityResult()中,通过
` if (intent != null) {
event.uri = intent.getData();
if (event.uri == null) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
event.uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), (Bitmap) bundle.get("data"), null, null));
}
}
`
可以拿到uri,但获得的图片是被压缩过的。若指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);输出路径,则此处的intent为null,但可以使用我们存的uri读取照片,此时的照片没有被压缩。
2.从相册中读取照片, 方法:
`
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
srcActivity.startActivityForResult(intent, ACTION_ALBUM);
`
即使设置 intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri(srcActivity));输出路径,仍然不能从此路径中读取,只能在onActivityForResult()中通过event.uri = intent.getData();方式获得图片uri。
此种现象也好理解,拍照时产生新的图片,自然可根据设置的uri进行图片保存,而读取相册时,图片已经在目录中不能转移到自己设定的uri中。
7.0以上版本如何访问uri
Androidmanifest.xml中
`
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.jd.tobs.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
android:readPermission="com.company.contentprovider.READ_DATABASE"
android:writePermission="com.company.contentprovider.WRITE_DATABASE">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>`
在 res/xml/provider_paths.xml
`
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="JDTobs" path=""/>
<files-path name="name" path="path" />
<cache-path name="name" path="path" /> <external-path name="name" path="path" />
<external-files-path name="name" path="path" />
<external-cache-path name="name" path="path" /> </paths> `
读取uri
` /**
* 获取临时图片Uri
*
* @return
*/
public static Uri getTempUri(Activity activity) {
Uri uri = null;
if (Build.VERSION.SDK_INT > 22) {
uri = FileProvider.getUriForFile(activity, "com.jd.tobs.fileprovider",
new File(FilePathProvider
.getAppImageFolderPath(), PHOTO_TEMP));
} else {
uri = Uri.fromFile(new File(FilePathProvider
.getAppImageFolderPath(), PHOTO_TEMP));
}
return uri;
}`