Getting permission denied when using a URI despite FLAG_GRANT_READ_URI_PERMISSION being set

心不动则不痛 提交于 2019-12-25 02:38:08

问题


I have two android apps A and B. I am passing a file from app A to app B and I am seeing that app B is getting the URI. I am setting the FLAG_GRANT_READ_URI_PERMISSION flag in app A and I am seeing that that mFlags is a 1, which is the value of FLAG_GRANT_READ_URI_PERMISSION, from within app B. This is all good, but when I try to create a FileInputStream from the URI, I get a FileNotFoundException (Permission denied) exception. What am I doing wrong?

Here are the pertinent code snippets:

In app A:

public void openTest Intent(String filePath) {
    Intent testIntent = new Intent("com.example.appB.TEST");
    testIntent.addCategory(Intent.CATEGORY_DEFAULT);
    testIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    testIntent.setDataAndType(Uri.parse("file://"+filePath),"text/plain");
    try {
        startActivityForResult(testIntent, OPEN_NEW_TERM);      
    } catch (ActivityNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

In app B:

@Override 
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if (intent.getAction().equals("com.example.appB.TEST")) {
        Uri fileUri = intent.getData();
        File srcFile = new File(fileUri.getPath());
        File destFolder = getFilesDir();
        File destFile = new File(destFolder.getAbsolutePath()+srcFile.getName());
        try {
            copyFile(srcFile,destFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

public void copyFile(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);  //**this is where it dies**
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

It is when I am creating in that it gets the exception. Any thoughts on why?


回答1:


What am I doing wrong?

You are trying to use FLAG_GRANT_READ_URI_PERMISSION for a file. That only works for content:// Uri values, pointing to a stream served by a ContentProvider.

Use FileProvider to serve up your files via such a ContentProvider. This is also covered in a training guide, and here is a sample project demonstrating its use.



来源:https://stackoverflow.com/questions/25416035/getting-permission-denied-when-using-a-uri-despite-flag-grant-read-uri-permissio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!