In Android, How can I display an application selector based on file type?

后端 未结 2 415
悲哀的现实
悲哀的现实 2021-01-02 20:01

Apologies if this has already been answered - if someone can point me to an already-answered question, that would be great...

Very simply, I would like to be able to

相关标签:
2条回答
  • 2021-01-02 20:19

    To get the applications that can successfully open a given intent you'll use the PackageManager. Simply construct the intent as above and then use this code to get the applications that can handle the intent.

    Intent myIntent = new Intent();
    myIntent.setAction(Intent.ACTION_VIEW);
    myIntent.addCategory("android.intent.category.LAUNCHER");
    myIntent.setType("mp3");    
    
    PackageManager manager = getPackageManager();
    List<ResolveInfo> info = manager.queryIntentActivities(
        myIntent, PackageManager.MATCH_DEFAULT_ONLY);
    

    This will give you all the information on the programs that can handle the intent, including icon, and packagename. You can then create a dialog box with these options and save the option the user chooses.

    0 讨论(0)
  • 2021-01-02 20:28

    I assume you want to see this chooser dialog if you do open a file (or URL) and there is more than one application registered to handle it? E.g. you open a youtube URL and can chose to use the youtube player or browser?

    That is the kind of intent the system sends when I want to open an image (through the file browser):

    File f = new File("/sdcard/IMG_0114.JPG");
    Uri uri = Uri.fromFile(f);
    
    Intent i = new Intent(Intent.ACTION_VIEW);
    // use setDataAndType() - setData() and setType() cancel each other
    i.setDataAndType(uri, "image/jpeg");
    i.putExtra("preview", false);
    i.putExtra("key_filename", "/sdcard/IMG_0114.JPG");
    i.putExtra(Intent.EXTRA_STREAM, uri);
    i.putExtra("sort_order", 0);
    
    // It's one of the flag combinations:
    i.setFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
    
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
            Intent.FLAG_ACTIVITY_SINGLE_TOP |
            Intent.FLAG_ACTIVITY_MULTIPLE_TASK |
            Intent.FLAG_DEBUG_LOG_RESOLUTION);
    
    startActivity(i);
    

    EDIT: corrected code to get a working (minimal) solution.

    I am not sure which fields of the extra data has to be set - didn't find documentation for that.

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