View Course Path

Intents in Android: Navigate to Web Pages within an App – Full Code and Tutorial

What will you learn?

  1. Using an Intent to navigate to webpage, given its URL link.
  2. Using OnClickListener on widgets.
  3. Handling errors and exceptions with try{} and catch{}.
  4. Parsing the Uri data into Intents.
  5. Using the createChooser() method for invoking user-friendliness.

Introduction

Browsing the web is definitely among the top hobbies of every person in the world! A significant portion of our screen time is spent surfing the internet. A web browser takes us anywhere on the internet. It retrieves information from other parts of the web and displays it on our desktop or mobile devices. The information is transferred using the Hypertext Transfer Protocol (HTTP), which defines how text, images and video are transmitted on the web. This information needs to be shared and displayed in a consistent format so that people using any browser, anywhere in the world can see the information.

In this post, we are going to learn how to launch the Web Browser in our phones through the app we will create. This indeed is done with the help of an Intent.

Requirements

In terms of the widgets required for the creation of this app, we don’t need much; because this is more of a theoretical tutorial, rather than a UI oriented one. Regardless, since we are going to launch intents on the user’s action, to open up the browser, we need a widget that can trigger some function when an action (for example, tap) is made on it. Hence, the widgets we will use to trigger intents are::

  1. Button/s: To launch intents for opening the browser once they’re tapped upon.

Let us now begin with the creation of our app.

Getting Started

The first thing to do is to open up the Android Studio. Once opened, create a new project with an Empty Activity as the default MainActivity. This is shown below:

Selecting the Activity
Selecting the Activity

Then, we select the minimum Android level and supported devices, click on “finish” and the project is built. We’re ready to work on it now!

Coding it Out

In this section, we would write the code to set up the User Interface and the functionality of our app. Let’s begin.

Step 1: Setting up the User Interface

First of all, we navigate to the activity_main.xml file where we will be putting in the Buttons to support the Intent launches which would lead us to the targeted web-pages in the web browser of our device. We don’t need to focus much upon the layout of the app, the functionality of it is of central importance. We simply put 3 buttons to navigate to 3 different web-pages (here, Instagram, Facebook and YouTube) when the user would click upon them. However, to make it look neat, they are put in a straight vertical column, with the help of the constraints which we set up using the ConstraintLayout as the base layout for the app. Also, it is important to rightly set the names of the buttons to clearly tell the user which button navigates to which website! After the necessary positioning, the button tags in our XML file should look like this:

<Button
    android:id="@+id/fbButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:text="Facebook"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/instaButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:text="Instagram"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/fbButton" />

<Button
    android:id="@+id/youtubeButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:text="Youtube"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/instaButton" />

The layout of our app screen takes the form:

Browser Intents UI
UI of the app

Next, we move over to the MainActivity.java file to link up the buttons to our code and set up the clicking functionalities for the buttons.

Step 2: Putting together the MainActivity

The foremost thing to do here, as you must have rightly guessed, is to link up the Button widgets to our Java code. For this, we first create Button variables for the widgets we created in the XML file above, and then link them together using the findViewById() method. This process is depicted below:

fbButton = (Button)findViewById(R.id.fbButton);
instaButton = (Button)findViewById(R.id.instaButton);
youtubeButton = (Button)findViewById(R.id.youtubeButton);

To bring in the clicking functionality, we make use of the OnClickListener function on the buttons. To induce re-usability of code and to make it look cleaner, we create a separate method clickedButton()  for launching the Intent, rather than writing the same piece of code in all the 3 OnClickListener methods. We pass the URL  to the targeted websites into a String variable in this method call. The code to carry out these steps is given below:

fbButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v)
    {
        clickedButton("https://www.facebook.com/");
    }
});

instaButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v)
    {
        clickedButton("https://www.instagram.com/");
    }
});

youtubeButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v)
    {
        clickedButton("https://www.youtube.com/");
    }
});

Now that we’ve completed the basic structure of the MainActivity, let’s head on to building the clickedButton() function, which would redirect us to a web browser we choose.

Step 3: Creating the Functionality of the Redirecting method

We initialize and Intent variable here, and use the constructor of the Intent library to give our intent an attribute of the type ACTION_VIEW, which is used to view a webpage. Also, we would need to to use the setData() method on our intent to specify the Uri data we are to deal with. And the Uri data which is to be attached to our intent here, is the URL of the webpage we are going to navigate to. Hence, we parse() the targeted URL as the Uri data and pass it into the setData() method. These steps are shown below:

public void clickedButton(String url)
{
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
}

The final step is to initiate the intent, directing us to a web browser of our choice to view the webpage. This is done with the help of the startActivity() method which is called upon the Intent variable. We would also require to prompt the user to make a choice of the browser of his liking, if there are multiple of them installed in his device. For this, we make use of the createChooser() method, which takes the Intent variable and a display message (which requests the user to make the choice) as its parameters. Also, the navigation might cause an error (due to reasons like incorrect URL, switching between apps, etc.), so it is better to enclose this code in a try-catch block. If an exception occurs, we simply tell the user that the link can’t be opened with the help of a Toast message. The code to all these steps is given below:

try
{
    startActivity(Intent.createChooser(intent, "Choose a Browser"));
}

catch(Exception e)
{
    Toast.makeText(getApplicationContext(), "Couldn't open the link!", Toast.LENGTH_SHORT).show();
}

And this leads us to the end of this tutorial! We hope you understood the entire procedure given above and are now able to integrate the Intents to open up the we browser successfully into your apps. Good luck with building them!

Full code for the MainActivity class

(Don’t forget to add your own package name on the top!)

Full code for the User Interface of the MainActivity

Related courses for this will be up soon!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.