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

标签 android android-intent

我正在尝试使用其他应用程序打开文件,即使用 Gallery 打开 .jpg,使用 Acrobat 打开 .pdf 等。

我遇到的问题是,当我尝试在应用程序中打开文件时,它只会打开所选的应用程序,而不是在应用程序中打开文件。我尝试关注 Android open pdf file via Intent但我一定遗漏了什么。

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 类型:

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

最佳答案

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

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);
}

关于Android - 如何通过 Intent 在另一个应用程序中打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31621419/

相关文章:

java - 检查 URL 的 mimetype 是否不是网页

android - 将数据从 json 对象显示到 android listview

java - Android 应用程序在 startActivity 上崩溃

安卓打开邮件客户端

android - 多个 Intent 的 onActivityResult

android - android Spinner 中的数据绑定(bind)错误

android - SVN不导入.so文件

java - ListView 项目打开新 Activity

设置和重置闹钟的 Android AlarmManager 问题

java - Android 错误锁定模式监听器