ACTION_VIEW intent for a file with unknown MimeType

后端 未结 13 1794
抹茶落季
抹茶落季 2020-11-27 10:57

My app has a feature that browse files on your phone and SD card and open them using other apps. I want a solution where I don\'t have to specify the MimeType and can work w

13条回答
  •  攒了一身酷
    2020-11-27 11:39

    You can find out the mime type of a file and make your own intent to open the file.

    Use the following code to open any file...

    File temp_file=new File("YOUR FILE PATH");
    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(temp_file),getMimeType(temp_file.getAbsolutePath()));
    startActivity(intent); 
    

    Where getMimeType() is....(this method will return desired mime type or null if the file does not have any proper mime type)...

    private String getMimeType(String url)
        {
            String parts[]=url.split("\\.");
            String extension=parts[parts.length-1];
            String type = null;
            if (extension != null) {
                MimeTypeMap mime = MimeTypeMap.getSingleton();
                type = mime.getMimeTypeFromExtension(extension);
            }
            return type;
        }
    

提交回复
热议问题