0% found this document useful (0 votes)
38 views17 pages

2.using Intents

An Android Intent is an abstract description of an operation to be performed. It can be used to launch activities, send broadcasts, and communicate with services. Intents contain action, data, category and other metadata to identify the component to perform the operation. There are explicit intents that designate a specific component class, and implicit intents that do not specify a class and rely on intent resolution to find a matching component.

Uploaded by

nithiyapriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views17 pages

2.using Intents

An Android Intent is an abstract description of an operation to be performed. It can be used to launch activities, send broadcasts, and communicate with services. Intents contain action, data, category and other metadata to identify the component to perform the operation. There are explicit intents that designate a specific component class, and implicit intents that do not specify a class and rely on intent resolution to find a matching component.

Uploaded by

nithiyapriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Using Intents:

 An Android Intent is an abstract description of an operation to be performed.


 It can be used with startActivity to launch an Activity, broadcastIntent to
send it to any interested BroadcastReceiver components,
and startService(Intent) or bindService(Intent, ServiceConnection,
int) to communicate with a background Service.
 The intent itself, an Intent object, is a passive data structure
holding an abstract description of an operation to be performed.
 For example, let's assume that you have an Activity that needs to launch an
email client and sends an email using your Android device. For this purpose,
your Activity would send an ACTION_SEND along with
appropriate chooser, to the Android Intent Resolver.
 The specified chooser gives the proper interface for the user to pick how to
send your email data.

Example:

Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));


email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
startActivity(Intent.createChooser(email, "Choose an email client from..."));
 For example, assume that you have an Activity that needs to open URL in a
web browser on your Android device. For this purpose, your Activity will send
ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given
URL in the web browser.
 The Intent Resolver parses through a list of Activities and chooses the one that
would best match your Intent, in this case, the Web Browser Activity.
 The Intent Resolver then passes your web page to the web browser and starts
the Web Browser Activity.

String q = "tutorialspoint";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);

 Above example will search as tutorialspoint on android search engine and it


gives the result of tutorialspoint in your an activity
 There are separate mechanisms for delivering intents to each type of
component − activities, services, and broadcast receivers.

Sr.No Method & Description

Context.startActivity()

1 The Intent object is passed to this method to launch a new activity or get an
existing activity to do something new.

Context.startService()

2 The Intent object is passed to this method to initiate a service or deliver new
instructions to an ongoing service.

Context.sendBroadcast()

3 The Intent object is passed to this method to deliver the message to all
interested broadcast receivers.
Exploring Intent Objects:

 An Intent object is a bundle of information which is used by the component


that receives the intent as well as information used by the Android system.
 An Intent object can contain the following components based on what it is
communicating or going to perform.
1. Action
 This is mandatory part of the Intent object and is a string naming the action to
be performed — or, in the case of broadcast intents, the action that took place
and is being reported.
 The action largely determines how the rest of the intent object is structured.
 The Intent class defines a number of action constants corresponding to
different intents. Here is a list of Android Intent Standard Actions
 The action in an Intent object can be set by the setAction() method and read
by getAction().
2. Data
 Adds a data specification to an intent filter. The specification can be just a data
type (the mimeType attribute), just a URI, or both a data type and a URI.
 A URI is specified by separate attributes for each of its parts & These
attributes that specify the URL format are optional, but also mutually
dependent –
o If a scheme is not specified for the intent filter, all the other URI
attributes are ignored.
o If a host is not specified for the filter, the port attribute and all the
path attributes are ignored.
 The setData() method specifies data only as a URI, setType() specifies it only
as a MIME type, and setDataAndType() specifies it as both a URI and a MIME
type.
 The URI is read by getData() and the type by getType().

Some examples of action/data pairs are −

Sr.No. Action/Data Pair & Description


ACTION_VIEW content://contacts/people/1
1
Display information about the person whose identifier is "1".

ACTION_DIAL content://contacts/people/1
2
Display the phone dialer with the person filled in.

ACTION_VIEW tel:123
3
Display the phone dialer with the given number filled in.

ACTION_DIAL tel:123
4
Display the phone dialer with the given number filled in.

ACTION_EDIT content://contacts/people/1
5
Edit information about the person whose identifier is "1".

ACTION_VIEW content://contacts/people/
6
Display a list of people, which the user can browse through.

ACTION_SET_WALLPAPER
7
Show settings for choosing wallpaper

ACTION_SYNC

8 It going to be synchronous the data,Constant Value


is android.intent.action.SYNC

ACTION_SYSTEM_TUTORIAL
9
It will start the platform-defined tutorial(Default tutorial or start up
tutorial)

ACTION_TIMEZONE_CHANGED
10
It intimates when time zone has changed

ACTION_UNINSTALL_PACKAGE
11
It is used to run default uninstaller

3. Category
 The category is an optional part of Intent object and it's a string containing
additional information about the kind of component that should handle the
intent. The addCategory() method places a category in an Intent object,
removeCategory() deletes a category previously added, and getCategories()
gets the set of all categories currently in the object. Here is a list of Android
Intent Standard Categories.
 You can check detail on Intent Filters in below section to understand how do
we use categories to choose appropriate activity corresponding to an Intent.
4. Extras
 This will be in key-value pairs for additional information that should be
delivered to the component handling the intent.
 The extras can be set and read using the putExtras() and getExtras() methods
respectively. Here is a list of Android Intent Standard Extra Data
5. Flags
 These flags are optional part of Intent object and instruct the Android system
how to launch an activity, and how to treat it after it's launched etc.

Sr.No Flags & Description

FLAG_ACTIVITY_CLEAR_TASK

1 If set in an Intent passed to Context.startActivity(), this flag will cause any


existing task that would be associated with the activity to be cleared before
the activity is started. That is, the activity becomes the new root of an
otherwise empty task, and any old activities are finished. This can only be
used in conjunction with FLAG_ACTIVITY_NEW_TASK.

FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current
2 task, then instead of launching a new instance of that activity, all of the
other activities on top of it will be closed and this Intent will be delivered to
the (now on top) old activity as a new Intent.

FLAG_ACTIVITY_NEW_TASK

This flag is generally used by activities that want to present a "launcher"


3 style behavior: they give the user a list of separate things that can be done,
which otherwise run completely independently of the activity launching
them.

6. Component Name
 This optional field is an android ComponentName object representing
either Activity, Service or BroadcastReceiver class.
 If it is set, the Intent object is delivered to an instance of the designated class
otherwise Android uses other information in the Intent object to locate a
suitable target.
 The component name is set by setComponent(), setClass(), or setClassName()
and read by getComponent().

Types of Intents

 There are following two types of intents supported by Android


1. Implicit Intent
2. Explicit Intent

Explicit Intents
 Explicit intent going to be connected internal world of application, suppose if
you wants to connect one activity to another activity, we can do this quote by
explicit intent, below image is connecting first activity to second activity by
clicking button.

 These intents designate the target component by its name and they are
typically used for application-internal messages - such as an activity starting a
subordinate service or launching a sister activity. For example −

// Explicit Intent by specifying its class name


Intent i = new Intent(FirstActivity.this, SecondActivity.class);

// Starts TargetActivity
startActivity(i);
Implicit Intents

 These intents do not name a target and the field for the component name is
left blank.
 Implicit intents are often used to activate components in other applications.
For example −

Intent read1=new Intent();


read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);
Exploring Intent Resolution

Because of the arbitrary nature of Implicit Intents, the system uses a process
called Intent Resolution to map them correctly. The system does this by matching
the Intent description with the default descriptions in the system.

Intent Object, defined earlier comes into play here. The Intent Resolution
compares the contents of Intent Object against the Intent Filters. (Intent Filters
are associated with the different Android components, and can receive
Intent. Intent filter is a way for Android components to declare their
capabilities to the Android system.)

Filters play an important role in defining the kind of intent an Android


component can receive. A component with no filters can receive only Explicit Intents,
whereas components with filters are capable of receiving both Explicit and Implicit
Intents.

The Intent Resolution uses the following information to map the Intent to the
appropriate Android component:

 The action
 The type (data type and URI)
 The category

Exploring Intent Filters

 You have seen how an Intent has been used to call an another activity.
Android OS uses filters to pinpoint the set of Activities, Services, and
Broadcast receivers that can handle the Intent with help of specified set of
action, categories, data scheme associated with an Intent.

 You will use <intent-filter> element in the manifest file to list down actions,
categories and data types associated with any activity, service, or broadcast
receiver.

 Following is an example of a part of AndroidManifest.xml file to specify an


activity com.example.My Application. CustomActivity which can be
invoked by either of the two mentioned actions, one category, and one data −
<activity android:name=".CustomActivity"
android:label="@string/app_name">

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.My Application.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>

</activity>

Linking the Activities Using Intent

 Once this activity is defined along with above mentioned filters, other
activities will be able to invoke this activity using either the
android.intent.action.VIEW, or using the com.example.My
Application.LAUNCH action provided their category is
android.intent.category.DEFAULT.

 The <data> element specifies the data type expected by the activity to be
called and for above example our custom activity expects the data to start with
the "http://"

 There may be a situation that an intent can pass through the filters of more
than one activity or service, the user may be asked which component to
activate. An exception is raised if no target can be found.

There are following test Android checks before invoking an activity −

 A filter <intent-filter> may list more than one action as shown above but this
list cannot be empty; a filter must contain at least one <action> element,
otherwise it will block all intents. If more than one actions are mentioned then
Android tries to match one of the mentioned actions before invoking the
activity.
 A filter <intent-filter> may list zero, one or more than one categories. if there
is no category mentioned then Android always pass this test but if more than
one categories are mentioned then for an intent to pass the category test, every
category in the Intent object must match a category in the filter.
 Each <data> element can specify a URI and a data type (MIME media type).
There are separate attributes like scheme, host, port, and path for each
part of the URI. An Intent object that contains both a URI and a data type
passes the data type part of the test only if its type matches a type listed in the
filter.

Example

Create a project in Android Studio and named it “Intents”. Make an activity, which
would consists Java file; MainActivity.java and an xml file for User interface which
would be activity_main.xml
Step 1: Let’s design the UI of activity_main.xml:

 First design the text view displaying basic details of the App
 Second design the two button of Explicit Intent Example and Implicit Intent

Below is the complete code of activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"

android:text="If you click on Explicit example we will navigate to second activity


within App and if you click on Implicit example AbhiAndroid Homepage will open in
Browser"

android:id="@+id/textView2"

android:clickable="false"

android:layout_alignParentTop="true"

android:layout_alignParentStart="true"

android:layout_marginTop="42dp"

android:background="#3e7d02"

android:textColor="#ffffff" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Explicit Intent Example"

android:id="@+id/explicit_Intent"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="147dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Implicit Intent Example"

android:id="@+id/implicit_Intent"

android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Step 2: Design the UI of second activity activity_second.xml

Now lets design UI of another activity where user will navigate after he click on
Explicit Example button. Go to layout folder, create a new activity and name it
activity_second.xml.

 In this activity we will simply use TextView to tell user he is now on second
activity.

Below is the complete code of activity_second.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

android:background="#CCEEAA"

tools:context="com.example.android.intents.SecondActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:text="This is Second Activity"


android:id="@+id/textView"

android:layout_centerVertical="true"

android:layout_centerHorizontal="true" />

</RelativeLayout>

Step 3: Implement onClick event for Implicit And Explicit Button inside
MainActivity.java

Now we will use setOnClickListener() method to implement OnClick event on both


the button. Implicit button will open AbhiAndroid.com homepage in browser and
Explicit button will move to SecondActivity.java.

Below is the complete code of MainActivity.java

package com.example.android.intents;

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;

public class MainActivity extends AppCompatActivity {

Button explicit_btn, implicit_btn;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

explicit_btn = (Button)findViewById(R.id.explicit_Intent);

implicit_btn = (Button) findViewById(R.id.implicit_Intent);


//implement Onclick event for Explicit Intent

explicit_btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Intent intent = new Intent(getBaseContext(), SecondActivity.class);

startActivity(intent);

});

//implement onClick event for Implicit Intent

implicit_btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setData(Uri.parse("https://www.abhiandroid.com"));

startActivity(intent);

});

Step 4: Create A New JAVA class name SecondActivity

Now we need to create another SecondActivity.java which will simply open the layout
of activity_second.xml . Also we will use Toast to display message that he is on
second activity.

Below is the complete code of SecondActivity.java:


package com.example.android.intents;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

public class SecondActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second);

Toast.makeText(getApplicationContext(), "We are moved to second


Activity",Toast.LENGTH_LONG).show();

Step 5: Manifest file:

Make sure Manifest file has both the MainActivity and SecondActivity listed it. Also
here MainActivity is our main activity which will be launched first. So make sure
intent-filter is correctly added just below MainActivity.

Below is the code of Manifest file:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.android.intents" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme" >

<activity android:name=".MainActivity" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity android:name=".SecondActivity" >

</activity>

</application>

</manifest>

Output:

Now run the above program in your Emulator. The App will look like this:

You might also like