Android11,无法使用intent打开已存在的docx文件
创始人
2024-09-30 18:30:19
0

在Android 11中,应用程序需要处理与存储访问框架(SAF)相关的更改。在访问不在应用专用存储空间中的文件时,应使用SAF而不是直接使用文件路径进行访问。

以下代码示例演示如何通过使用SAF从文件选择器打开docx文件:

private static final int REQUEST_CODE_OPEN_DOCUMENT = 2;

public void openWordDocument() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("*/*"); // set MIME type to filter files
    intent.putExtra(Intent.EXTRA_TITLE, "Open Word File");
    startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    super.onActivityResult(requestCode, resultCode, resultData);

    if (requestCode == REQUEST_CODE_OPEN_DOCUMENT && resultCode == Activity.RESULT_OK) {
        Uri uri = resultData.getData();
        String path = getFilePathFromURI(getActivity(), uri);
        openDocxFileWithIntent(path);
    }
}

private String getFilePathFromURI(Context context, Uri uri) {
    String filePath = "";
    if (uri.getScheme().equals("file")) {
        filePath = uri.getPath();
    } else {
        try {
            ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
            if (pfd != null) {
                FileDescriptor fd = pfd.getFileDescriptor();
                filePath = context.getCacheDir().getAbsolutePath() + "/" + uri.getLastPathSegment();
                FileOutputStream fos = new FileOutputStream(filePath);
                FileInputStream fis = new FileInputStream(fd);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fis.close();
                fos.close();
                pfd.close();
                fd.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return filePath;
}

private void openDocxFileWithIntent(String filePath) {
    if (!filePath.isEmpty()) {
        File file = new File(filePath);
        Intent intent =

相关内容

热门资讯

扑克之星辅助!wejoker透... 扑克之星辅助!wejoker透视方法(透视)器-本来关于有挂1、该软件可以轻松地帮助玩家将wejok...
wepoker免费透视脚本!红... wepoker免费透视脚本!红龙poker辅助工具(透视)教程-一贯必备存在有挂1、打开软件启动之后...
hhpoker辅助靠谱吗!we... hhpoker辅助靠谱吗!wepoker辅助脚本(透视)器-本来揭幕真的有挂1、打开软件启动之后找到...
wepoker好友房开挂!we... wepoker好友房开挂!wepoker网页版透视方法(透视)教程-原来了解存在有挂wepoker网...
wepoker手机版透视脚本!... wepoker手机版透视脚本!wpk透视(透视)神器-其实专业有挂1、下载好wepoker手机版透视...
菠萝德普辅助器免费版在哪里!p... 菠萝德普辅助器免费版在哪里!pokerrrr2辅助(透视)器-切实必备是真的挂一、菠萝德普辅助器免费...
微乐小程序黑科技!微乐家乡官方... 微乐小程序黑科技!微乐家乡官方免费下载安装(开挂)app-原来必备是真的挂1、起透看视 辅助软件价格...
微信小程序黑科技免费!微信微乐... 微信小程序黑科技免费!微信微乐陕西小程序辅助器(开挂)教程-竟然有挂存在有挂1、不需要AI权限,帮助...
微乐小程序存在有挂!微乐家乡官... 微乐小程序存在有挂!微乐家乡官方app(开挂)方法-好像专业是有挂进入游戏-大厅左侧-新手福利-激活...
微乐小程序存在有挂!微乐河南小... 微乐小程序存在有挂!微乐河南小程序微乐辅助脚本(开挂)方法-确实分享有挂1、实时透视辅助更新:用户可...