Blog

Android: Opening a webpage in your app using Intents

Opening up a website from an application in android is very simple thanks to “Intents”. An Intent is a request to android use an application to preform a task. The code below shows a very simple example of launching a browser to go to the wordcube website.

Context context = getApplicationContext();
String url = "http://www.stealthcopter.com/wordcube";
Intent i = new Intent(Intent.ACTION_VIEW); 
Uri u = Uri.parse(url); 
i.setData(u); 
try {
  // Start the activity
  startActivity(i);
} catch (ActivityNotFoundException e) {
  // Raise on activity not found
  Toast toast = Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}

As pointed out in the comments, the context can be replaced by the activity itself, such as TestApp.this. eg:

Toast toast = Toast.makeText(TestApp.this, "Browser not found.", Toast.LENGTH_SHORT);

We have surrounded the activity with a try/catch which will be raised if android cannot find an application that will accept this intent, in this case a web-browser. It is highly unlikely that an android phone will not have a web-browser installed but it is a good practise to get into.

10 Comments

  1. Mark Murphy

    You don’t need the getApplicationContext() line. Just use whatever Activity, Service, etc. your code is running in, as they are all subclasses of Context. Also, you can put the Uri in the Intent constructor rather than in a separate setData() call: new Intent(Intent.ACTION_VIEW, Uri.parse(“http://www.stealthcopter.com/wordcube”))

  2. mat

    Yes I usually use TestApp.this or whatever to call this function, I just wanted to show an example that would work independently.

  3. Android

    You need to show your Toast messages or they don’t show up.

    Toast.makeText(TestApp.this, “Browser not found.”, Toast.LENGTH_SHORT).show();

    And of course in production code, your using resource strings, right? 😉

  4. jenny word

    Just nice

  5. Mithun S

    Is there any way to pass a value back to the called App??
    APP1-> APP2->APP1 ???

  6. GeethaDevi

    Interesting approach opening a web page in app using intents..Thanks a lot.. Android Training

  7. XeaDah

    r http://tadalafil-ph24.com/ generic cheap cialis

  8. Virgilio Guebara

    Thanks a lot for the blog post. Really looking forward to reading more.

  9. rithu rawat

    Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information’s.

  10. kavi

    Such a Great Article!! I learned something new from your blog. Amazing stuff. I would like to follow your blog frequently. Keep Rocking!!

Leave a Comment

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