Launching an intent for file and MIME type?

前端 未结 2 359
孤独总比滥情好
孤独总比滥情好 2020-12-02 17:45

I\'ve reviewed all the similar questions here, but I can\'t for the life of me figure out what I\'m doing wrong.

I\'ve written an application that tries to launch va

相关标签:
2条回答
  • 2020-12-02 18:24

    Well thanks to the Open Intent guys, I missed the answer the first time through their code in their file manager, here's what I ended up with:

        File file = new File(filePath);
        MimeTypeMap map = MimeTypeMap.getSingleton();
        String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
        String type = map.getMimeTypeFromExtension(ext);
    
        if (type == null)
            type = "*/*";
    
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data = Uri.fromFile(file);
    
        intent.setDataAndType(data, type);
    
        startActivity(intent);
    

    If you use a mime type of "* / *" when you can't determine it from the system(it is null) it fires the appropriate select application dialog.

    0 讨论(0)
  • 2020-12-02 18:29

    You can use generic intents to open files,like this snippet code that is proposed here:

    private void openFile(File aFile){
        try {
            Intent myIntent = new Intent(android.content.Intent.VIEW_ACTION,
            new ContentURI("file://" + aFile.getAbsolutePath()));
            startActivity(myIntent);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }     
    

    But I usually see that Applications checks the file's extension in nested if and finally try to open file with "text/plain" type:

    Intent generic = new Intent();
    generic.setAction(android.content.Intent.ACTION_VIEW);
    generic.setDataAndType(Uri.fromFile(file), "text/plain");     
    try {
        startActivity(generic);
        } catch(ActivityNotFoundException e) {
        ...
    }     
    

    You can see complete code in this question or in this open source project. I hope this help you.

    0 讨论(0)
提交回复
热议问题