[TUT] Button to open web browser

By blundell  

Someone requested this so here goes:

If you want to send someone to a website when they press a button in your activity:

MainActivity class:

package com.blundell.twitterlink;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.main); //Set the screen's view to your xml file
        Button twitterButton = (Button) findViewById(R.id.twitterButton); // Retrieve the button from the XML file
        twitterButton.setOnClickListener(new View.OnClickListener() {  //Add a listener for when the button is pressed
                        public void onClick(View v) {
        protected void sendToTwitter() {
                String url = "http://twitter.com/blundell_apps"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
                Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
                i.setData(Uri.parse(url));  // Add the url data (allowing android to realise you want to open the browser)
                startActivity(i); // Go go go!

And your XML layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:text="Send me to Twitter"

As always, enjoy!


  1. Fraser Dixon
    Posted February 6, 2013 at 8:01 pm | Permalink | Reply

    Hi Blundell,

    Firstly thanks for your awesome tutorials. I’m just dipping my toes in developing and have found it really useful.
    Could you direct me in how I could create a custom “splash”? screen for the ‘button to opena web browser?
    I’ve basically got myself in a situation where I’ll need to produce a load of these launchers and would rather know/learn how to do it with expert guidance than pay someone a monthly charge to create and manage such apps. That said, I’ll happily give you a tutorial fee if you can help me :-)
    Many thanks,

Post a Comment

Your email is never shared. Required fields are marked *