授予Uri允许其他活动

nne*_*rov 7 android android-permissions

我正在尝试从设备库中获取图像,然后在另一个活动中显示它.我活动中的代码:

private void startGallery() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");
    startActivityForResult(intent, REQ_OPEN_GALLERY)
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQ_OPEN_GALLERY &&  resultCode == Activity.RESULT_OK) {
        Uri imageUri = data.getData()
        // here I save image uri to pass to another activity
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在另一项活动中打开uri时,我得到了SecurityException.Docs表示,获得uri的许可将持续到收到它们的活动完成为止.所以当我的活动结束时,我没有读取文件的权限.

是否有某种方法可以延长uri的许可,允许其他活动通过此uri打开文件?或者唯一的方法是将图像复制到本地应用程序存储?

UPD:我的目标是将收到的uri保存在本地数据库中,并允许其他活动和服务读取此文件.

Com*_*are 11

是否有某种方法可以延长uri的许可,允许其他活动通过此uri打开文件?

是.包括FLAG_GRANT_READ_URI_PERMISSION当您通过Uri从第一个活动的第二项活动:

startActivity(new Intent(this, Something.class).setData(uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION));
Run Code Online (Sandbox Code Playgroud)

  • @nnesterov:"我的目标是在本地数据库中保存收到的uri" - 这是行不通的.如果你在Android 4.4+上使用`ACTION_OPEN_DOCUMENT`,你可以尝试使用`takePersistableUriPermission()`,如果有效,你可以长期访问`Uri`标识的内容.否则,您需要制作内容的本地副本.有关此操作的演示,请参阅[此示例应用程序](https://github.com/commonsguy/cw-omnibus/tree/master/Documents/Durable). (2认同)