Pages

Monday 18 April 2011

Quick Tip: Opening a URI in the web browser

Below is example code to open a web page URI / URL in the web browser:

  String webPageUri = "http://android-elements.blogspot.com/";
  Uri uri = Uri.parse(webPageUri);
  if (uri != null) {
    Intent myIntent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(myIntent);
  }

First we parse the uri string. If we have a non-null value we create a new Intent object set to use ACTION_VIEW with the uri as a parameter. ACTION_VIEW will perform the appropriate action for the contents of the provided uri. Then we call a method to start the new activity with this intent object.

Finally, we must ensure the app has internet access to call a web page (see my list of common Android pitfalls) so add the following permission to the manifest:

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


Review the Android Developers site for more on intents and my Android Building Blocks guide for getting started.

0 comments:

Post a Comment