Intent to open link in browser does not work

Posted on

Question :

How do I get my button to send the user to a link?

String url = "LINK";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

I tried this way but it did not work

    

Answer :

Your code is correct.

What should be happening is to be using a URL without the protocol, such as “google.com”.

The URL should include the “http: //” or “https: //” protocol.

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

You can create a method that ensures that the link has the added protocol:

public static browseTo(String url){

    if (!url.startsWith("http://") && !url.startsWith("https://")){
        url = "http://" + url;
    }
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);
}

    

Leave a Reply

Your email address will not be published. Required fields are marked *