android 拍照使用fileprovider遇到的坑

废话少说,直接进入正题。
最大的坑是:

Process: com.android.camera2, PID: 20419                                     java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{4238a238 20419:com.android.camera2/u0a30} (pid=20419, uid=10030) that is not exported from uid 10143

其实字面意思上已经很好理解了,缺少权限,注意:5.0以上的手机是不会报这个错的
然后我就在网上搜,应该会有这方面的资料吧,搜了好长时间,国外的网站都翻了,除了exported和grantUriPermissions在manifest上设置外,竟然没有别的资料。
第二天,我觉得可能是我搜得不对,终于我搜到了一个靠谱的

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

我想,这回肯定没问题了,但是结果总是出乎你的意料之外,竟然还是报错~~~~
这可咋整,接着搜,点开一篇文章,没报什么希望,是介绍7.0的拍照调用fileprovider的,嗯?有不一样的设置

 List resInfoList= getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, photoURI,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }

试试吧,一试,成了,太激动了,这是一款4.4.4的手机,没毛病~~~
还有一款4.2.2的手机,一试,这个还报错,想了想,这个list循环只加了write权限,估计是缺少read权限,一加,果然好使!
就此,这个深坑解决啦,希望别的网友也能看到这篇帖子
最后链接上给我思路的博客:
http://www.jianshu.com/p/a1eb3ad79ef6
感谢!
最后附上拍照源码:

private void take() {
        // 激活系统的照相机进行拍照
        String filePath = AppConfig.CIVIL_WORKER_PATH + AppConfig.CHECK_PHOTO;
        File outputFile = new File(filePath);
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdir();
        }
        Uri photoURI = FileProvider.getUriForFile(activity,
                getPackageName() + ".fileprovider", outputFile);
        //为拍摄的图片指定一个存储的路径
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //设置权限
        List resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            grantUriPermission(packageName, photoURI,                   Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.putExtra("camerasensortype", 1); // 调用后置摄像头
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        startActivityForResult(intent, REQUEST_TAKE_PICTURE);
    }
 private static final int REQUEST_TAKE_PICTURE = 100;//照相
  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_TAKE_PICTURE) {
            String filePath = AppConfig.CIVIL_WORKER_PATH + AppConfig.CHECK_PHOTO;
            Bitmap bitmap = BitmapUtils.getimage(filePath);
        }
    }

OVER

你可能感兴趣的:(android学习之路)