Intents are a fundamental topic for Android developers. It is impossible to build Android applications without coming in contact with intents. In this tutorial, I’ll teach you about intents from A to Z.
What Are Intents?
In a football match, teammates pass the ball around the field with the aim of sending it into the goal of their opponent. The ball is passed from the team’s goalkeeper to their defenders. Next, it finds its way to the midfielders, and if things work out as planned, one of the strikers sends it into the net of the opponent. That’s assuming the goalkeeper of the other side was not able to keep it away!
In Android, the ability to send messages around is made possible by the Intent
object. With the help of intents, Android components can request functionality from other Android components. When you open up the Instagram app on your phone and use it to take a picture, you just made use of an intent. Intents also help communicate between parts of an app; the movement from one screen (activity) to another is made possible by intents.
Look at it this way: all components (applications and screens) of the Android device are isolated. The only way they communicate with each other is through intents.
Starting Activities With Intents
As mentioned earlier, you can use intents to start different components: activities, services, and broadcast receivers.
To start an activity, you will make use of the method startActivity
(intent)
.
Here is a code snippet that demonstrates how to start another activity from an intent.
Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class); startActivity(numbersIntent);
First, we create a new Intent
object and pass it the NumbersActivity
class. Then we start a new activity using that intent.
Types of Intents
Android supports two types of intents: explicit and implicit. When an application defines its target component in an intent, that it is an explicit intent. When the application does not name a target component, that it is an implicit intent.
Explicit Intent Example
The code snippet of code above is an example of explicit intent. Have a look at it again.
Intent numbersIntent = new Intent(MainActivity.this, NumbersActivity.class); startActivity(numbersIntent);
Here, NumbersActivity
is the target component from our MainActivity
. This means that NumbersActivity
is the defined component that will be called by the Android system. It is important to note (as in the example above), that explicit intents are typically used within an application, because that gives the developer the most control over which class will be launched.
Implicit Intent Example
Here’s an implicit intent:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.tutsplus.com")); startActivity(intent);
If you have the above code in your codebase, your application can start a browser component for a certain URL via an intent. But how does the Android system identify the components which can react to a certain intent?
A component can be registered via an intent filter for a specific action. Intent filters can be registered for components statically in the AndroidManifest.xml. Here is an example that registers a component as a web viewer:
Using Intents in an App
Let’s write some code to see how it works out. In this section, you’ll build a tiny app to try out both styles of intent. The app will have a little form to enter a first name and last name. When the Submit button is clicked, both of the entered values will be passed to another activity. There will also be a button to launch a browser of your choice. The chosen browser will open up http://code.tutsplus.com.
Open up Android Studio and generate your MainActivity
. You can set the name of the package to com.tutsplus.code.android.droidintent.
Your MainActivity
will start with some imports and the class declaration:
package com.tutsplus.code.android.droidintent; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { }
Then you’ll override the onCreate()
method to initialize the activity with any saved state and the activity layout (we’ll create this later).
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // button handlers go here }
Next you’ll get references to each of the buttons defined in the layout and attach a click listener to each of them.
final Button submitButton = (Button) findViewById(R.id.submit_button); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText firstName = (EditText) findViewById(R.id.first_name_text); EditText lastName = (EditText) findViewById(R.id.last_name_text); String firstNameString = firstName.getText().toString(); String lastNameString = lastName.getText().toString(); Intent submitIntent = new Intent(MainActivity.this, ShowActivity.class); submitIntent.putExtra("firstNameString", firstNameString); submitIntent.putExtra("lastNameString", lastNameString); startActivity(submitIntent); } });
For the Submit button, you set an OnClickListener
to trigger an action whenever the button is clicked. When a click occurs, we grab the first and last name from the view, and send them to the next activity: ShowActivity
. The target component is explicitly defined in the intent, making this an example of explicit intent.
final Button browserButton = (Button) findViewById(R.id.browser_button); browserButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://code.tutsplus.com")); startActivity(intent); } });
For the browser button, the OnClickListener
will create a new intent to launch any application that matches the filter: an ACTION_VIEW
which should handle a web URL. In other words, it launches a web browser. If you have more than one browser application installed on your device, you will be asked to select one to perform the action of opening the web site. This is an example of an implicit intent.
MainActivity
Layout
The layout for MainActivity
will be very simple for the purpose of this tutorial.
Here you have two TextView
and two EditText
indicating First Name and Last Name respectively. There is also a button to submit the names, and another to launch your browser.
Create the ShowActivity
To complete our app, we need to create an activity to handle the explicit intent defined above. Create a new activity called ShowActivity
. This is the activity where the result of entering the first name and last name will be shown. Here is what it should look like:
package com.tutsplus.code.android.droidintent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class ShowActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); Bundle extras = getIntent().getExtras(); String inputFirstName = extras.getString("firstNameString"); String inputLastName = extras.getString("lastNameString"); TextView showFirstName = (TextView) findViewById(R.id.show_first_name); TextView showLastName = (TextView) findViewById(R.id.show_last_name); showFirstName.setText(inputFirstName); showLastName.setText(inputLastName); } }
In this activity, you start by getting the strings passed from the MainActivity
. You can get a reference to the intent that triggered the launch of this activity with the getIntent()
function. Then you can access the strings that were passed to it using getExtras().getString()
. Finally, after getting the TextView instances from the layout, you display the values you obtained.
ShowActivity Layout
The layout for this activity is simple:
Testing the App
Now you can build your app and try it out on your Android device!
Passing Data Using Bundles
You can also make use of Bundles when passing data via intents.
The Bundle
class allows you store complex data and supports data types such as strings, chars, boolean, integer and so on. Here is an example of how part of MainActivity.java would look if you used Bundle
.
// Creating Bundle object Bundle b = new Bundle(); // Storing data into bundle b.putString("firstNameString", firstNameString); b.putString("lastNameString", lastNameString); // Creating Intent object Intent submitIntent = new Intent(MainActivity.this, ShowActivity.class); // Storing bundle object into intent submitIntent.putExtra(b); startActivity(submitIntent);
Conclusion
In this tutorial, we got a brief introduction to using intents to create activities in Android. We looked at the difference between explicit and implicit intents, and coded a simple example that used each type.
You can read more about intents in the Android documentation. Understanding how they work is very important. As you build more apps, you will encounter lots of different kinds of Intents and ways of using them.
And in the meantime, check out some of our other posts on Android app development!
-
Android SDKIntroduction to Android Architecture Components
-
JavaAndroid Design Patterns: The Observer Pattern
-
AndroidAndroid From Scratch: Building Your First Android Application