Automatically open Intent Chooser for the file And

2019-02-10 23:16发布

I want to open a file in android. What i want to do is if the file is of type Image then i want to open Intent Chooser which contains applications that can view the image, and if it is of video type, then open Intent Chooser with applications that can view videos. How can i achieve this?

2条回答
时光不老,我们不散
2楼-- · 2019-02-10 23:27

I have found a solution. I am pasting it here so it may help other users.

    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().indexOf(".") + 1);
    String type = mime.getMimeTypeFromExtension(ext);

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

    context.startActivity(intent);
查看更多
淡お忘
3楼-- · 2019-02-10 23:42

You should decide and know whether the file is video or image. You may do it by looking at the extension of the files.

After that you can open videos like this:

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

and images like this:

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

Android system will open the Intent Chooser automatically.

查看更多
登录 后发表回答