牛轧糖中的媒体图像文件被阻止且权限被拒绝

Media image file Blocked and permission denied in nougat

我在用转换后的位图图像替换捕获图像时遇到错误。

Intent intent =new Intent(this,Myclass.class);
intent.setData(params[0]);
sendBroadcast(intent);

正在广播中 class

Uri uri=intent.getData();

复制方法

private File CopyImage(String sourcepath, String targetpath) {
        File sourceLocation = new File(sourcepath);
        File targetLocation = new File(targetpath);
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(sourceLocation);
            out = new FileOutputStream(targetLocation);
            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return targetLocation;
    }

当我访问目标路径时

content://media/external/images/media/19392?blocking=1&orig_id=19392&group_id=0

已授予权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

您是否分配了如下 运行 时间权限,

private int REQUEST_READ_PERMISSION=1;
 private boolean checkAndRequestPermissions() {

        int externalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        List<String> listPermissionsNeeded = new ArrayList<>();


        if (externalStoragePermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(mActivity, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_READ_PERMISSION);

            return false;
        }
        return true;

    }

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(REQUEST_READ_PERMISSION ==requestCode)
        {

        }
    }

When I am accessing the targetpath

那不是一条路。即 Uri 的字符串表示形式。 Uri 不是文件。

所以:

  • String targetpath替换为Uri target

  • 去掉File targetLocation = new File(targetpath);

  • ContentResolver 传递到方法中,您可以通过在 Context

  • 上调用 getContentResolver() 获得该方法
  • out = new FileOutputStream(targetLocation); 替换为 out = cr.openOutputStream(target); 其中 cr 是您的 ContentResolver