How can I open a URL in Android's web browser from my application?

前端 未结 30 2773
庸人自扰
庸人自扰 2020-11-21 22:09

How to open an URL from code in the built-in web browser rather than within my application?

I tried this:

try {
    Intent myIntent = new Intent(Int         


        
30条回答
  •  一整个雨季
    2020-11-21 22:50

    So I've looked for this for a long time because all the other answers were opening default app for that link, but not default browser and that's what I wanted.

    I finally managed to do so:

    // gathering the default browser
    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
    final ResolveInfo resolveInfo = context.getPackageManager()
        .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    String defaultBrowserPackageName = resolveInfo.activityInfo.packageName;
    
    
    final Intent intent2 = new Intent(Intent.ACTION_VIEW);
    intent2.setData(Uri.parse(url));
    
    if (!defaultBrowserPackageName.equals("android") {
        // android = no default browser is set 
        // (android < 6 or fresh browser install or simply no default set)
        // if it's the case (not in this block), it will just use normal way.
        intent2.setPackage(defaultBrowserPackageName);
    }
    
    context.startActivity(intent2);
    

    BTW, you can notice context.whatever, because I've used this for a static util method, if you are doing this in an activity, it's not needed.

提交回复
热议问题