Launching the Browser in Android with Xamarin

If you like the Android interface and have used an app like Facebook or Twitter, you’re no doubt used to the ability to click a link and get a list of browser-based applications to choose from. This ability to choose your browser to open a link is a feature in Android called an “intent”. An intent is an asynchronous message to request some action on behalf of another application. Intents serve many purposes, such as sending data to Facebook, or a browser. Intents also navigate between activities in an application.

For sharing to a browser, it requires using a special intent with is the Intent.ACTION_VIEW in Android, or Intent.ActionView in Xamarin Android. This intent, along with the URL, signals to Android to open the requested resource in a browser. For instance, let’s take a look at the following method:

private void ShareToBrowser(string url)
{
	if (!url.StartsWith ("http")) {
		url = "http://" + url;
	}

	Android.Net.Uri uri = Android.Net.Uri.Parse(url);
	Intent intent = new Intent (Intent.ActionView);
	intent.SetData (uri);

	Intent chooser = Intent.CreateChooser (intent, "Open with");

	this.StartActivity(chooser);
}

In our utility method, from an URL string, we ensure there is an “http” prefix on the URL; otherwise, the intent doesn’t quite work right. From the URL, we create an Android URI, and pass it as the data of the intent. The constructor of the intent takes the name of an action, which in our case, is the view action. In most other common situations, we’d use the Send action. The View action is used for browsing, whereas Send is used for app sharing (to Facebook, etc.)

If we were to start the activity without the chooser, Android would pick the first browser installed and launch it. By adding a “chooser” intent, we get that nice “Open with” dialog, listing all of our installed browsers. And it’s that simple to launch the browser in our application.

If you are looking for a nice overview of intents, Lars Vogel has a nice overview available at Vogella.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s