ACTION_VIEW intent for a file with unknown MimeType

后端 未结 13 1845
抹茶落季
抹茶落季 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:34

    This should detect the mimetype and open with default:

    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    Intent newIntent = new Intent(Intent.ACTION_VIEW);
    String mimeType = myMime.getMimeTypeFromExtension(fileExt(getFile()).substring(1));
    newIntent.setDataAndType(Uri.fromFile(getFile()),mimeType);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        context.startActivity(newIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, "No handler for this type of file.", Toast.LENGTH_LONG).show();
    }
    

    Using this function:

    private String fileExt(String url) {
        if (url.indexOf("?") > -1) {
            url = url.substring(0, url.indexOf("?"));
        }
        if (url.lastIndexOf(".") == -1) {
            return null;
        } else {
            String ext = url.substring(url.lastIndexOf(".") + 1);
            if (ext.indexOf("%") > -1) {
                ext = ext.substring(0, ext.indexOf("%"));
            }
            if (ext.indexOf("/") > -1) {
                ext = ext.substring(0, ext.indexOf("/"));
            }
            return ext.toLowerCase();
    
        }
    }
    

提交回复
热议问题