Android launch browser without specifying a URL

前端 未结 3 1986
误落风尘
误落风尘 2021-01-18 20:20

How would one go about launching the browser from an activity without specifying a url. I would like to open the browser so the user can continue browsing without changing t

相关标签:
3条回答
  • 2021-01-18 20:50

    In case it (the ComponentName("com.android.browser", "com.android.browser.BrowserActivity")) changes in the future, you may try something like the following code:

    public static ComponentName getDefaultBrowserComponent(Context context) {
        Intent i = new Intent()
            .setAction(Intent.ACTION_VIEW)
            .setData(new Uri.Builder()
                    .scheme("http")
                    .authority("x.y.z")
                    .appendQueryParameter("q", "x")
                    .build()
                    );
        PackageManager pm = context.getPackageManager();
        ResolveInfo default_ri = pm.resolveActivity(i, 0); // may be a chooser
        ResolveInfo browser_ri = null;
        List<ResolveInfo> rList = pm.queryIntentActivities(i, 0);
        for (ResolveInfo ri : rList) {
            if (ri.activityInfo.packageName.equals(default_ri.activityInfo.packageName)
             && ri.activityInfo.name.equals(default_ri.activityInfo.name)
            ) {
                return ri2cn(default_ri);
            } else if ("com.android.browser".equals(ri.activityInfo.packageName)) {
                browser_ri = ri;
            }
        }
        if (browser_ri != null) {
            return ri2cn(browser_ri);
        } else if (rList.size() > 0) {
            return ri2cn(rList.get(0));
        } else if (default_ri == null) {
            return null;
        } else {
            return ri2cn(default_ri);
        }
    }
    private static ComponentName ri2cn(ResolveInfo ri) {
        return new ComponentName(ri.activityInfo.packageName, ri.activityInfo.name);
    }
    

    Basically, here I construct an intent to view a dummy http page, get the list of activities that may handle the intent, compare it to the default handler returned by resolveActivity() and return something. I do not need to check if there's a launcher MAIN action (my code uses the VIEW action), but you probably should.

    0 讨论(0)
  • 2021-01-18 20:59

    Use Intent#setComponent() to set the Browser's package and class name. Then start the activity.

    0 讨论(0)
  • this answer may help. from How to open the default android browser without specifying an URL?

    PackageManager pm = getPackageManager();
    Intent queryIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
    ActivityInfo af = queryIntent.resolveActivityInfo(pm, 0);
    Intent launchIntent = new Intent(Intent.ACTION_MAIN);
    launchIntent.setClassName(af.packageName, af.name);
    startActivity(launchIntent);
    
    0 讨论(0)
提交回复
热议问题