Android - 如何通过Intent在另一个应用程序中打开文件?

23

我正在尝试使用其他应用程序打开文件,例如使用画廊打开.jpg,使用Acrobat打开.pdf等。

我的问题是当我尝试在应用程序中打开文件时,它只会打开所选的应用程序,而不是在应用程序内打开文件。我尝试遵循Android通过Intent打开pdf文件,但我可能错过了一些步骤。

public String get_mime_type(String url) {
    String ext = MimeTypeMap.getFileExtensionFromUrl(url);
    String mime = null;
    if (ext != null) {
        mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
    }
    return mime;
}

public void open_file(String filename) {
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), filename);

    // Get URI and MIME type of file
    Uri uri = Uri.fromFile(file).normalizeScheme();
    String mime = get_mime_type(uri.toString());

    // Open file with user selected app
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(uri);
    intent.setType(mime);
    context.startActivity(Intent.createChooser(intent, "Open file with"));
}
据我所知,它返回了正确的URI和MIME类型:

As far as I can tell, it returns the right URI and MIME type:

URI: file:///storage/emulated/0/Download/Katamari-ringtone-985279.mp3
MIME: audio/mpeg

只是一个小提示,在setData()之后调用setType()会清除数据,所以最好使用setDataAndType() - Lukas
2个回答

41
发布我的更改,以防能帮助其他人。我最终将下载位置更改为内部文件夹并添加了内容提供程序。

发布我的更改,以防能帮助其他人。我最终将下载位置更改为内部文件夹并添加了内容提供程序。

public void open_file(String filename) {
    File path = new File(getFilesDir(), "dl");
    File file = new File(path, filename);

    // Get URI and MIME type of file
    Uri uri = FileProvider.getUriForFile(this, App.PACKAGE_NAME + ".fileprovider", file);
    String mime = getContentResolver().getType(uri);

    // Open file with user selected app
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, mime);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);
}

1
我尝试在我的应用程序中使用它,但它的行为很奇怪。我尝试了谷歌搜索,但没有答案。这种方法适用于一些第三方应用程序,但对其他一些应用程序不起作用。我下载文件并发送意图,但是有些第三方应用程序无法打开它。如果我使用浏览器下载相同的文件,并使用相同的第三方应用程序从浏览器(或文件管理器)打开该文件,则可以正常工作。我认为浏览器和文件管理器在发送意图时有一个棘手的秘密。你有什么想法吗? - bdevay
谢谢。你让我的一天变得更美好了,伙计。 - KhoaHA
@devay 我遇到了同样的问题。你解决了吗?如果是这样,能帮我一下吗? - Roshan S

-1

我使用了这段代码,在安卓6及以下版本上运行良好,但在更高版本上未经过测试。

public void openFile(final String fileName){
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory()
            .getAbsolutePath()+ File.separator+"/Folder/"+fileName));
    intent.setDataAndType(uri, "audio/mpeg");
    startActivity(intent);
}

2
这只能打开音频/mpeg文件类型,不是所有类型的文件,需要说明。 - Durgesh Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接