Intent in Android
All about Intent in Android - Using Java and Android Studio
Introduction
The Intent is a mechanism that helps users move from one activity to another within the same application and other applications.
It is mainly used to
- start an activity
- start a service
- send messages between two activities, etc.
For example, while using some android application, we click on a phone number, and it automatically dials it. This is done with the help of Intent.
Intents are classified into two categories:
Implicit Intent
Here, no component is specified; instead, an action is performed. In the above code snippet, an implicit intent is declared to view a webpage(URL).
Explicit Intent
Here, the component is specified, i.e., the external class to be invoked is provided. In the above code snippet, an explicit intent is declared to move from one activity to another.
Building Blocks of an Intent
Component name
The component name represents the component's name (or component category) to start. Optional, used while declaring an explicit intent and a service.
Action
Action represents the action to be taken/performed - ACTION_VIEW
and ACTION_SEND
.
ACTION_VIEW
is used to show some information to the user.
ACTION_SEND
is used to share some data using a 3rd party application.
Action can be set in two ways.
Data
Data represents the type of data to be sent.
For data URI, setData()
is called and for the MIME type, setType()
is called.
Extras
Extras are the key-value pairs that contain extra information to perform the requested action. The extras are specified in putExtra()
method.
NOTE
setData()
is used to point to the location of a data object (like a file).putExtra()
adds simple data types (such as a text string).
Flags
Flags instruct the Android system on how to launch activity and treat it after it is launched. To set the flags, setFlags()
method is used.
For example, FLAG_ACTIVITY_CLEAR_TASK
finished all the old activities (associated with the activity) before starting the activity via the startActivity()
method.
Examples
Sending data with Intent from one activity to another (First Activity -> Second Activity)
Sharing text data with other application
Sharing an image file with other application
Dialing a number
Sending an email to a group of email-addresses
In this way, we can use Intent to view the information to the user, to share the data among different activities and different applications, etc.