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

时间:2017-06-30 13:00:18

标签: android image camera capture mediastore

在将转换后的位图替换为捕获图像时,我遇到了错误。

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

中的

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" />

2 个答案:

答案 0 :(得分:1)

  

当我访问目标路径时

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

所以:

  • String targetpath替换为Uri target

  • 摆脱File targetLocation = new File(targetpath);

  • ContentResolver传递给您在getContentResolver()

  • 上致电Context后获得的方法
  • out = new FileOutputStream(targetLocation);替换为out = cr.openOutputStream(target);,其中cr是您的ContentResolver

答案 1 :(得分:0)

您是否获得了如下所示的运行时权限,

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)
        {

        }
    }