自动打开Android文件的意图选择器。

问题描述 投票:5回答:2

我想打开一个文件,在 android. 我想做的是,如果文件的类型是 Image 然后我想打开 Intent Chooser 其中包含可以查看图片的应用程序,如果是视频类型,则打开可以查看视频的应用程序的意图选择器。我如何实现这个功能?

android file android-intent mime-types
2个回答
13
投票

我已经找到了一个解决方案。我把它粘贴在这里,所以它可能会帮助其他用户。

    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);
    File file = new File(path);

    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1);
    String type = mime.getMimeTypeFromExtension(ext);

    intent.setDataAndType(Uri.fromFile(file), type);

    context.startActivity(intent);

1
投票

你应该决定并知道该文件是视频还是图像。你可以通过查看文件的扩展名来确定。

之后你就可以打开这样的视频。

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse(result), "video/*");
startActivity(intent);

而图片则是这样的

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse(result), "image/*");
startActivity(intent);

Android 系统会打开 Intent Chooser 自动。

© www.soinside.com 2019 - 2024. All rights reserved.