title: Get Preferred/Default app on Android
body: <p>I am trying to get the default/preferred application for a given <code>Intent</code>. For example, when the user installs a second web browser, then attempts to open a URL, he or she will get a dialog like this:</p>
  
  <p><img src="https://i.stack.imgur.com/6Knpl.jpg" alt="default browser selector"></p>
  
  <p>If the user then selects the <em>Use by default for this action</em> option, then the dialog box no longer opens when a URL is pressed.</p>
  
  <p>I am working on an application that should be aware of what this <em>default</em> or <em>preferred</em> app/action is. How do I do this? I am currently using the code below, but <code>getPreferredPackage</code> doesn't return anything:</p>
  
  <pre><code>Intent i = (new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
  PackageManager pm = context.getPackageManager();
  final List&lt;ResolveInfo&gt; list = pm.queryIntentActivities(i, 0);
  IntentFilter ifilter = new IntentFilter(i.getAction());
  if (i.getCategories() != null) {
      for(String category : i.getCategories()) {
          ifilter.addCategory(category);
      }
  }
  List&lt;IntentFilter&gt; filters = new ArrayList&lt;IntentFilter&gt;();
  filters.add(ifilter);
  List&lt;ComponentName&gt; preferredActivities = new ArrayList&lt;ComponentName&gt;();
  pm.getPreferredActivities(filters, preferredActivities, null);
  for (ComponentName activity : preferredActivities) {
      for (ResolveInfo rinfo : list) {
          if (rinfo.activityInfo.applicationInfo.packageName.equals(activity.getPackageName())) {
              try {
                  final PackageInfo pi = pm.getPackageInfo(activity.getPackageName(), 0);
                  Toast.makeText(context, pm.getApplicationLabel(pi.applicationInfo), Toast.LENGTH_SHORT).show();
              }
          } catch (NameNotFoundException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>What am I doing wrong? Is this even the right approach?</p>