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