Android Developer Tutorials and Blog

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. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(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
@Override
public void onClick(View v) {
sendToTwitter();
}
});
}
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!
}
}

2 thoughts on “[TUT] Button to open web browser”

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,
Fraser