ChatGPT解决这个技术问题 Extra ChatGPT

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

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(Intent.ACTION_VIEW, Uri.parse(download_link));
    startActivity(myIntent);
} catch (ActivityNotFoundException e) {
    Toast.makeText(this, "No application can handle this request."
        + " Please install a webbrowser",  Toast.LENGTH_LONG).show();
    e.printStackTrace();
}

but I got an Exception:

No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
I think it's because of this: android-developers.blogspot.com/2009/12/…
Why this is not working in some devices? even if there is a web browser, it goes to ActivityNotFoundException.
I'm seeing the same issue as @Manu. Basic install on a Nexus 6, has chrome, but links causing an exception.
can i hide address bar? @Arutha

V
Vishal Chhodwani

Try this:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

That works fine for me.

As for the missing "http://" I'd just do something like this:

if (!url.startsWith("http://") && !url.startsWith("https://"))
   url = "http://" + url;

I would also probably pre-populate your EditText that the user is typing a URL in with "http://".


Except that your code and mbaird's aren't the same, from what I can tell for what's posted. Ensure that your URL has the http:// scheme -- the exception shown suggests that your URL is lacking the scheme.
Yes ! It missed the http:// ! The URL is entered by the user, is there a way to automatically format?
URLUtil is a great way to check on user entered "url" Strings
if (!url.startsWith("http://") && !url.startsWith("https://")) is a common error which may lead you to urls like file:// and break some good usecases. Try to parse uri with URI class and check is there a schema. If no, add "http://" ;)
You need null check with resolveCheck. See the offical docs : Caution: If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object.
N
Nimantha

A common way to achieve this is with the next code:

String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url)); 
startActivity(i); 

that could be changed to a short code version ...

Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));      
startActivity(intent); 

or :

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")); 
startActivity(intent);

the shortest! :

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));

F
Flimm

Simple Answer

You can see the official sample from Android Developer.

/**
 * Open a web page of a specified URL
 *
 * @param url URL to open
 */
public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

How it works

Please have a look at the constructor of Intent:

public Intent (String action, Uri uri)

You can pass android.net.Uri instance to the 2nd parameter, and a new Intent is created based on the given data url.

And then, simply call startActivity(Intent intent) to start a new Activity, which is bundled with the Intent with the given URL.

Do I need the if check statement?

Yes. The docs says:

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

Bonus

You can write in one line when creating the Intent instance like below:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

This presumes that the supplied url has http in it.
Check this out for handle https links on API 30+ stackoverflow.com/questions/2201917/…
M
MikeNereson

In 2.3, I had better luck with

final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);

The difference being the use of Intent.ACTION_VIEW rather than the String "android.intent.action.VIEW"


waht is the different ?
This answer helped me immensely. I do not know what the difference was, but we had an issue with 2.3 that this solved. Does anyone know what the difference in the implementation is?
According to Android Developer: this answer - "Create an intent with a given action. All other fields (data, type, class) are null." and the accepted answer - "Create an intent with a given action and for a given data url."
m
madlymad

Try this:

Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));

or if you want then web browser open in your activity then do like this:

WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);

and if you want to use zoom control in your browser then you can use:

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);

Note that plugins and such are disabled in WebView, and that the INTERNET permissions would be required. (reference)
M
MilaDroid

If you want to show user a dialogue with all browser list, so he can choose preferred, here is sample code:

private static final String HTTPS = "https://";
private static final String HTTP = "http://";

public static void openBrowser(final Context context, String url) {

     if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
            url = HTTP + url;
     }

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)

}

if there are multiple apps that can handle the intent, the system will automatically provide a chooser, right?
@xmen-w-k because url can start ether with http or https, and in java it is a good practice to declare 'magic strings' as constants.
thx, didn't know about context.startActivity. Very useful when calling it from an external class
A
Akito

The Kotlin answer:

val browserIntent = Intent(Intent.ACTION_VIEW, uri)
ContextCompat.startActivity(context, browserIntent, null)

I have added an extension on Uri to make this even easier

myUri.openInBrowser(context)

fun Uri?.openInBrowser(context: Context) {
    this ?: return // Do nothing if uri is null

    val browserIntent = Intent(Intent.ACTION_VIEW, this)
    ContextCompat.startActivity(context, browserIntent, null)
}

As a bonus, here is a simple extension function to safely convert a String to Uri.

"https://stackoverflow.com".asUri()?.openInBrowser(context)

fun String?.asUri(): Uri? {
    return try {
        Uri.parse(this)
    } catch (e: Exception) {
        null
    }
}

It doesn't add anything interesting. Even won't work if there is no application handling a URL. Will crash with an exception.
All devices should have an application to handle a URL. You can add your own failure/exception handling as needed,
Agree with you.
a
android developer

Just like the solutions other have written (that work fine), I would like to answer the same thing, but with a tip that I think most would prefer to use.

In case you wish the app you start to open in a new task, indepandant of your own, instead of staying on the same stack, you can use this code:

final Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);

There is also a way to open the URL in Chrome Custom Tabs . Example in Kotlin :

@JvmStatic
fun openWebsite(activity: Activity, websiteUrl: String, useWebBrowserAppAsFallbackIfPossible: Boolean) {
    var websiteUrl = websiteUrl
    if (TextUtils.isEmpty(websiteUrl))
        return
    if (websiteUrl.startsWith("www"))
        websiteUrl = "http://$websiteUrl"
    else if (!websiteUrl.startsWith("http"))
        websiteUrl = "http://www.$websiteUrl"
    val finalWebsiteUrl = websiteUrl
    //https://github.com/GoogleChrome/custom-tabs-client
    val webviewFallback = object : CustomTabActivityHelper.CustomTabFallback {
        override fun openUri(activity: Activity, uri: Uri?) {
            var intent: Intent
            if (useWebBrowserAppAsFallbackIfPossible) {
                intent = Intent(Intent.ACTION_VIEW, Uri.parse(finalWebsiteUrl))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
                        or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
                if (!CollectionUtil.isEmpty(activity.packageManager.queryIntentActivities(intent, 0))) {
                    activity.startActivity(intent)
                    return
                }
            }
            // open our own Activity to show the URL
            intent = Intent(activity, WebViewActivity::class.java)
            WebViewActivity.prepareIntent(intent, finalWebsiteUrl)
            activity.startActivity(intent)
        }
    }
    val uri = Uri.parse(finalWebsiteUrl)
    val intentBuilder = CustomTabsIntent.Builder()
    val customTabsIntent = intentBuilder.build()
    customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
            or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
    CustomTabActivityHelper.openCustomTab(activity, customTabsIntent, uri, webviewFallback)
}

Will making a new task protect the source app from bugs and crashing, in case the web browser have problems?
@TheOriginalAndroid I don't understand what it has to do with crashes and web browser. Please explain what you are trying to do.
Thanks for your response. Your post is interesting. What is the benefit of opening a new task especially for a web launch?
@TheOriginalAndroid Just so that the user will be able to switch back to your app, and then back again to the web browser. If you open recent-tasks screen, you will see 2 tasks here instead of one. Also, instead of seeing a web browser thumbnail in the single task (that belongs to your app's task), you will see 2 : one of your app, and another of the web browser. I think it's less confusing this way.
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET is deprecated
m
madlymad

other option In Load Url in Same Application using Webview

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");

Note that plugins and such are disabled in WebView, and that the INTERNET permissions would be required. (reference)
Also note that .setJavaScriptEnabled(true); is dangerous.
A
Aristo Michael

You can also go this way

In xml :

<?xml version="1.0" encoding="utf-8"?>
<WebView  
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

In java code :

public class WebViewActivity extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

 }

}

In Manifest dont forget to add internet permission...


This is interesting and different. I guess this way the user sees a web browser in my app. Is that right? I upvote.
G
Gorav Sharma

Webview can be used to load Url in your applicaion. URL can be provided from user in text view or you can hardcode it.

Also don't forget internet permissions in AndroidManifest.

String url="http://developer.android.com/index.html"

WebView wv=(WebView)findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

i
iSS

Within in your try block,paste the following code,Android Intent uses directly the link within the URI(Uniform Resource Identifier) braces in order to identify the location of your link.

You can try this:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);

J
Jorgesys

A short code version...

 if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
     strUrl= "http://" + strUrl;
 }


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));

U
Umasankar

Simple and Best Practice

Method 1:

String intentUrl="www.google.com";
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
    if(webIntent.resolveActivity(getPackageManager())!=null){
        startActivity(webIntent);    
    }else{
      /*show Error Toast 
              or 
        Open play store to download browser*/
            }

Method 2:

try{
    String intentUrl="www.google.com";
    Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
        startActivity(webIntent);
    }catch (ActivityNotFoundException e){
                /*show Error Toast
                        or
                  Open play store to download browser*/
    }

Use context!!.packageManager instead of getPackageManager() in a Fragment.
b
bopol

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.


b
benka
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

x
xjcl

Short & sweet Kotlin helper function:

private fun openUrl(link: String) =
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)))

A
Abhishek Balani
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));          
startActivity(getWebPage);

welcome, newbie. please make the answer more complete, declaring variables that do not exist in original code.
J
Juan Carlos Velez

The response of MarkB is right. In my case I'm using Xamarin, and the code to use with C# and Xamarin is:

var uri = Android.Net.Uri.Parse ("http://www.xamarin.com");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);

This information is taked from: https://developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/


m
madlymad

Chrome custom tabs are now available:

The first step is adding the Custom Tabs Support Library to your build.gradle file:

dependencies {
    ...
    compile 'com.android.support:customtabs:24.2.0'
}

And then, to open a chrome custom tab:

String url = "https://www.google.pt/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

For more info: https://developer.chrome.com/multidevice/android/customtabs


m
madlymad

Simple, website view via intent,

Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);  

use this simple code toview your website in android app.

Add internet permission in manifest file,

<uses-permission android:name="android.permission.INTERNET" /> 

c
chia yongkang

A new and better way to open link from URL in Android 11.

  try {
        val intent = Intent(ACTION_VIEW, Uri.parse(url)).apply {
            // The URL should either launch directly in a non-browser app
            // (if it’s the default), or in the disambiguation dialog
            addCategory(CATEGORY_BROWSABLE)
            flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER or
                    FLAG_ACTIVITY_REQUIRE_DEFAULT
        }
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        // Only browser apps are available, or a browser is the default app for this intent
        // This code executes in one of the following cases:
        // 1. Only browser apps can handle the intent.
        // 2. The user has set a browser app as the default app.
        // 3. The user hasn't set any app as the default for handling this URL.
        openInCustomTabs(url)
    }

References:

https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9 and https://developer.android.com/training/package-visibility/use-cases#avoid-a-disambiguation-dialog


N
Nimantha

I checked every answer but what app has deeplinking with same URL that user want to use?

Today I got this case and answer is browserIntent.setPackage("browser_package_name");

e.g. :

   Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
    browserIntent.setPackage("com.android.chrome"); // Whatever browser you are using
    startActivity(browserIntent);

Good answer. It explains how to open an Intent URL on a specific browser (directly), and not rely on the system picking a browser.
Great, this will open the verified link in chrome browser instead of your app, but what if chrome is not installed, you need to handle that case as well.
@shanraisshan Indeed
d
divonas

Based on the answer by Mark B and the comments bellow:

protected void launchUrl(String url) {
    Uri uri = Uri.parse(url);

    if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
        uri = Uri.parse("http://" + url);
    }

    Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);

    if (browserIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(browserIntent);
    }
}

I'd hire you any day .. Caring Code. Thanks
I
I.G. Pascual

android.webkit.URLUtil has the method guessUrl(String) working perfectly fine (even with file:// or data://) since Api level 1 (Android 1.0). Use as:

String url = URLUtil.guessUrl(link);

// url.com            ->  http://url.com/     (adds http://)
// http://url         ->  http://url.com/     (adds .com)
// https://url        ->  https://url.com/    (adds .com)
// url                ->  http://www.url.com/ (adds http://www. and .com)
// http://www.url.com ->  http://www.url.com/ 
// https://url.com    ->  https://url.com/
// file://dir/to/file ->  file://dir/to/file
// data://dataline    ->  data://dataline
// content://test     ->  content://test

In the Activity call:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URLUtil.guessUrl(download_link)));

if (intent.resolveActivity(getPackageManager()) != null)
    startActivity(intent);

Check the complete guessUrl code for more info.


G
Gaurav Lambole

Simply go with short one to open your Url in Browser:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);

possible to open it in the APP only, like within webview or something.
M
Mayur Sojitra
String url = "https://www.thandroid-mania.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
    Uri uri = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}else{
    Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}

That error occurred because of invalid URL, Android OS can't find action view for your data. So you have validate that the URL is valid or not.


C
Cube

Kotlin

startActivity(Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(your_link)
        })

D
Denis Royz

I think this is the best

openBrowser(context, "http://www.google.com")

Put below code into global class

    public static void openBrowser(Context context, String url) {

        if (!url.startsWith("http://") && !url.startsWith("https://"))
            url = "http://" + url;

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        context.startActivity(browserIntent);
    }

Z
Zoe stands with Ukraine

This way uses a method, to allow you to input any String instead of having a fixed input. This does save some lines of code if used a repeated amount of times, as you only need three lines to call the method.

public Intent getWebIntent(String url) {
    //Make sure it is a valid URL before parsing the URL.
    if(!url.contains("http://") && !url.contains("https://")){
        //If it isn't, just add the HTTP protocol at the start of the URL.
        url = "http://" + url;
    }
    //create the intent
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)/*And parse the valid URL. It doesn't need to be changed at this point, it we don't create an instance for it*/);
    if (intent.resolveActivity(getPackageManager()) != null) {
        //Make sure there is an app to handle this intent
        return intent;
    }
    //If there is no app, return null.
    return null;
}

Using this method makes it universally usable. IT doesn't have to be placed in a specific activity, as you can use it like this:

Intent i = getWebIntent("google.com");
if(i != null)
    startActivity();

Or if you want to start it outside an activity, you simply call startActivity on the activity instance:

Intent i = getWebIntent("google.com");
if(i != null)
    activityInstance.startActivity(i);

As seen in both of these code blocks there is a null-check. This is as it returns null if there is no app to handle the intent.

This method defaults to HTTP if there is no protocol defined, as there are websites who don't have an SSL certificate(what you need for an HTTPS connection) and those will stop working if you attempt to use HTTPS and it isn't there. Any website can still force over to HTTPS, so those sides lands you at HTTPS either way

Because this method uses outside resources to display the page, there is no need for you to declare the INternet permission. The app that displays the webpage has to do that