Android11打开文件失败:EACCES(Permissiondenied),是否可以使用ACTION_OPEN_DOCUMENT解决?
创始人
2024-08-20 10:00:18
0

可以使用ACTION_OPEN_DOCUMENT解决该问题。下面是相关示例代码:

在Manifest文件中添加以下权限:



在需要打开文件的Activity中添加以下代码:

private static final int REQUEST_CODE_OPEN_DOCUMENT = 2;

private void openFile() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == REQUEST_CODE_OPEN_DOCUMENT 
            && resultCode == Activity.RESULT_OK 
            && resultData != null) {
        Uri uri = resultData.getData();
        // 根据Uri获取文件路径示例代码:
        String path = getRealPathFromURI(this, uri);
        // 打开文件示例代码:
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse(path), "application/pdf");
        startActivity(intent);     
    }
}

private String getRealPathFromURI(Context context, Uri uri) {
    String filePath = "";
    if (uri.getScheme().compareTo("content") == 0) {
        Cursor cursor = context.getContentResolver().query(uri, 
                new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, 
                null, null, null);
        cursor.moveToFirst();
        filePath = cursor.getString(0);
        cursor.close();
    } else {
        filePath = uri.getPath();
    }
    return filePath;
}

在onActivityResult方法中处理返回的文件Uri,并调用getRealPathFromURI方法将Uri转为文件路径,然后可以使用该路径打开文件。注意:在Android 11中对外部存储的访问需要使用特殊权限,在查询Uri的数据时要使用MediaStore API。

相关内容

热门资讯

透视有挂!wepoker脚本,... 透视有挂!wepoker脚本,pokemmo脚本最新版,科技教程(素来存在有挂);(需添加指定Q群1...
透视透视挂!aapoker辅助... 透视透视挂!aapoker辅助工具存在吗,wepoker透视最简单三个步骤,2025版教程(一直是有...
透视黑科技!wepoker透视... 透视黑科技!wepoker透视脚本安卓,佛手大菠萝辅助,透明挂教程(原来有挂);亲,其实确实真的有挂...
透视科技!wepoker辅助器... 透视科技!wepoker辅助器安装包,德普之星透视免费,AI教程(真是真的有挂);大神普及一款德州a...
透视插件!aapoker透视脚... 透视插件!aapoker透视脚本下载,werplan外卦神器,2025新版教程(一向是真的有挂)1、...
透视计算!aapoker透视脚... 透视计算!aapoker透视脚本,拱趴大菠萝万能辅助器,透明教程(果然真的是有挂);玩家必备必赢加哟...
透视插件!wpk有脚本吗,we... 透视插件!wpk有脚本吗,wepoker私人局外卦,曝光教程(一直是有挂)1、每一步都需要思考,不同...
透视真的!wepoker脚本,... 透视真的!wepoker脚本,we poker辅助器下载,微扑克教程(从前是有挂)1、玩家可以在we...
透视黑科技!wepoker透视... 透视黑科技!wepoker透视脚本苹果版,we-poker有人玩吗,2025新版教程(确实真的是有挂...
透视教学!aapoker免费透... 透视教学!aapoker免费透视脚本,hhpoker软件靠谱吗,攻略教程(原本有挂);亲,其实确实真...