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 =

相关内容

热门资讯

透视揭露!wepoker辅助脚... 透视揭露!wepoker辅助脚本,wepoker私人局透视-确实是真的有辅助神器(哔哩哔哩)1、下载...
透视科普!wpk透视是真的假的... 透视科普!wpk透视是真的假的,wpk软件是正规的吗-真是存在有辅助软件(哔哩哔哩)1、金币登录送、...
透视解密!wepoker辅助真... 透视解密!wepoker辅助真的假的,We poker辅助器下载-真是真的有辅助神器(哔哩哔哩)亲,...
透视推荐!hhpoker辅助软... 透视推荐!hhpoker辅助软件,hhpoker德州有挂吗-果然是有辅助神器(哔哩哔哩)1、模拟器是...
透视科普!wpk透视是真的假的... 透视科普!wpk透视是真的假的,wpk辅助器是真的吗-真是是真的有辅助攻略(哔哩哔哩)1、有没有辅助...
透视曝光!wepoker可以透... 透视曝光!wepoker可以透视码,wejoker内置辅助-本来有辅助教程(哔哩哔哩)1、该软件可以...
透视揭露!wepoker破解工... 透视揭露!wepoker破解工具,wepoker怎么设置盖牌-本来一直总是有辅助方法(哔哩哔哩)1、...
透视有挂!有哪些免费的wpk作... 透视有挂!有哪些免费的wpk作弊码,wpk辅助器是真的吗-果然一直总是有辅助脚本(哔哩哔哩)1、公共...
透视关于!德扑圈透视挂,德普之... 透视关于!德扑圈透视挂,德普之星透视辅助-好像是真的有辅助软件(哔哩哔哩)脚本下载中分为三种模型:挂...
透视解密!德普辅助器怎么用,德... 透视解密!德普辅助器怎么用,德普之星透视-好像是有辅助app(哔哩哔哩)1、完成辅助器v3.3的残局...