Intent in Android

All about Intent in Android - Using Java and Android Studio

Intent in Android

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. carbon (2).png 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. carbon (1).png 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. carbon (7).png

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). carbon (8).png

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)

carbon (5).png

Sharing text data with other application

carbon (3).png

Sharing an image file with other application

carbon (4).png

Dialing a number

carbon (6).png

Sending an email to a group of email-addresses

carbon (9).png

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.