在Nougat 7中不支持Android相机裁剪

问题描述 投票:1回答:1

Android nougat 7中不支持相机和图库裁剪在android nougat 7中打开相机我收到此错误消息。

android.os.FileUriExposedException:

file:///storage/emulated/0/file1495176310055.jpg通过ClipData.Item.getUri()暴露在app之外

android camera crop android-7.0-nougat
1个回答
6
投票

对于面向Android 7.0的应用,Android框架会强制执行StrictMode API政策,该政策禁止在应用外部公开file:// URI。如果包含文件URI的意图离开您的应用程序,则应用程序将失败并显示FileUriExposedException异常。

要在应用程序之间共享文件,您应发送content:// URI并授予对URI的临时访问权限。授予此权限的最简单方法是使用FileProvider类。

你可以尝试我的解决方案..

1.add res / xml / provider_paths.xml

  provider_paths.xml
     <?xml version="1.0" encoding="utf-8"?>
     <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="images" path="."/>
     </paths>

2.在Manifest里面添加标签

     <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="android3.maxtingapp.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

3.在你的活动中添加作物图像的功能,就像我的样本下面一样

private void cropImage(File file) {
       final int width  = 400;
       final int height = 200;

   try {
    Intent cropIntent = new Intent("com.android.camera.action.CROP");

    Uri contentUri;

        if(Build.VERSION.SDK_INT > M){

             contentUri = FileProvider.getUriForFile(AddPlace.this,
                                   "android3.maxtingapp.provider",
                                    file);//package.provider

            //TODO:  Permission.. 

            getApplicationContext().grantUriPermission("com.android.camera",
                                                         contentUri,
            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

            cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            cropIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        }else{

            contentUri = Uri.fromFile(file);

        }

        cropIntent.setDataAndType(contentUri, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 2);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", width);
        cropIntent.putExtra("outputY", height);

        cropIntent.putExtra("return-data", true);
        startActivityForResult(cropIntent, REQUEST_CROP_ICON);

    }catch (ActivityNotFoundException a) {
        Log.e("Activity Not Found",""+a.toString());
    }
}

我希望这对某些人有帮助..

© www.soinside.com 2019 - 2024. All rights reserved.