美文网首页Android开发Android开发经验谈
Android7.0调用相机拍照问题

Android7.0调用相机拍照问题

作者: 猪爸爸Hulk | 来源:发表于2018-05-11 17:31 被阅读66次

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>

相关文章

网友评论

    本文标题:Android7.0调用相机拍照问题

    本文链接:https://www.haomeiwen.com/subject/ocofdftx.html