Open the native browser from an android app

后端 未结 6 1891
孤街浪徒
孤街浪徒 2020-12-30 11:26

I have an android phone with multiple browsers installed and I might or might not set a browser to default.

So, my question is..

  1. From my App, How do I
6条回答
  •  悲哀的现实
    2020-12-30 11:58

    Check this code:

    private final static List browserComponents  = new ArrayList() {{
        add(new ComponentName("com.google.android.browser", "com.google.android.browser.BrowserActivity"));
        add(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
        add(new ComponentName("com.android.chrome", "com.google.android.apps.chrome.IntentDispatcher"));
    }};
    
    public static void openInNativeBrowser(Context context, String url) {
        if (context == null || TextUtils.isEmpty(url)) {
            return;
        }
    
        PackageManager pm = context.getPackageManager();
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
    
        for (ComponentName cn : browserComponents) {
            intent.setComponent(cn);
            ActivityInfo ai = intent.resolveActivityInfo(pm, 0);
            if (ai != null) {
                aLog.w(TAG, "browser:  " + ai);
                context.startActivity(intent);
                return;
            } else {
                aLog.w(TAG, "can't resolve activity for " + intent);
            }
        }
    
        // no native browser
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        List list = pm.queryIntentActivities(intent, 0);
        if (list.size() > 0) {
            for (ResolveInfo ri : list) {
                aLog.w(TAG, ri + " : " + ri.isDefault);
            }
            context.startActivity(intent);
        } else {
            aLog.w(TAG, "no browser apps");
        }
    }
    

提交回复
热议问题