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
In 2.3, I had better luck with
The difference being the use of
Intent.ACTION_VIEW
rather than the String"android.intent.action.VIEW"
Simple Answer
You can see the official sample from Android Developer.
How it works
Please have a look at the constructor of
Intent
: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:
Bonus
You can write in one line when creating the Intent instance like below:
Try this one OmegaIntentBuilder
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:
Based on the answer by Mark B and the comments bellow:
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.
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:
Or if you want to start it outside an activity, you simply call startActivity on the activity instance:
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