Search code examples
androidandroid-file

How to set file or url "open with" programmatically?


enter image description here

When the file or url open, Android ask to user how to open with. My application need to set this option. I cannot completed to finish making application if no solution. Please tell me how to do.


Solution

  • If you share a file with Intent you can first create your Intent openWith object (but not run it yet). Then list all available activities for it like this:

    PackageManager pm = (Activity)this.getPackageManager();
    List<ResolveInfo> resInfo = pm.queryIntentActivities(openWith, 0);
    for (int i = 0; i < resInfo.size(); i++) {
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        String label = (String) ri.loadLabel(pm);
        String activity = ri.activityInfo.name;
        // choose needed packageName and activity here
    }
    

    Then add selected packageName and activity pair to the intent for "open with" action:

    intent.setComponent(new ComponentName(packageName, activity));
    

    and run it.