Android7.0后用调用拍照直接崩溃,报FileUriExposedException异常,以后Android7.0调用拍照就需要这样处理了。
public static void takePhoto(final Context context) {
File file = new File(IMAGE_PATH);
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}
File outFile = new File(IMAGE_PATH, "image.jpg");
if (outFile.exists()) {
outFile.delete();
}
try {
outFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT >= 24) {
intent.putExtra(MediaStore.EXTRA_OUTPUT,
FileProvider.getUriForFile(context, "com.goldou.ygty.fileprovider", outFile));
} else {
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
}
((Activity) context).startActivityForResult(intent, 102);
}
AndroidManifest.xml
添加provider,authorities的值是包名+.fileprovider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.goldou.ygty.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml
这里不加root-path的话会报IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Ygty/image.jpg异常,加上后正常运行。
<paths>
<external-path
name="camera_photos"
path="eg:/storage/emulated/0/Ygty" />
<root-path
name="root_path"
path="." />
</paths>