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:
<activity android:name=".BrowserActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http"/> </intent-filter> </activity>
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://ift.tt/1cWAN18.
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("http://ift.tt/1pw9ugf")); 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.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://ift.tt/nIICcg" xmlns:app="http://ift.tt/GEGVYd" xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent" android:orientation="vertical" android:layout_margin="16dp" android:layout_height="match_parent" tools:context="com.tutsplus.code.android.droidintent.MainActivity"> <TextView android:id="@+id/first_name_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter first name" /> <EditText android:id="@+id/first_name_text" android:padding="8dp" android:layout_width="200dp" android:layout_height="wrap_content" /> <TextView android:id="@+id/last_name_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter last name" /> <EditText android:id="@+id/last_name_text" android:layout_height="wrap_content" android:layout_width="200dp" android:padding="8dp" /> <Button android:id="@+id/submit_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submit"/> <Button android:id="@+id/browser_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:layout_marginLeft="100dp" android:text="Open Browser"/> </LinearLayout>
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:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://ift.tt/nIICcg" xmlns:app="http://ift.tt/GEGVYd" xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical" tools:context="com.tutsplus.code.android.droidintent.ShowActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="First Name:"/> <TextView android:id="@+id/show_first_name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Last Name:"/> <TextView android:id="@+id/show_last_name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
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
by Chinedu Izuchukwu via Envato Tuts+ Code
No comments:
Post a Comment