Você está na página 1de 54

UHD-CST Karzan H.

Sharif

Chapter Five
INTENTS AND BROADCAST RECEIVERS

Week Eight
Intents & Broadcast receiver

UHD-CST Karzan H. Sharif

Outline

Introducing Intents
AndroidManifest.xml file
Intent Class and Objects
Intents and App Components

Intent Object Info


Intent Types & Intent Filter
Data transfer to the target component
Broadcast Receivers
Creating the Broadcast Receiver
UHD-CST Karzan H. Sharif

Multiple Activities
Using intents each activity can start other activities
Each time a new activity is started, the previous activity is stopped and the system

preserves its stated


The Android system enables the flexible communication and data sharing between
components

This approach is called intent messaging

The requester sends a description of the operation requested to the Android system, which
locates receiver(s) that are capable of offering the requested service

UHD-CST Karzan H. Sharif

What are Intents?


Intents are a synchronous messages which allow application components to request
functionality from other Android components
Intents allow you to interact with components from the own and other applications
The Intent is created in the code of the Activity class

Allow us to use applications and components that are part of Android System
It also allows other applications to use the components of the applications we create
Through the startActivity(intent), you can define that the Intent should be used to
start an activity. You can also start service via intents, for example
startService(intent)

UHD-CST Karzan H. Sharif

What are Intents? (2)


You can use Intents to do the following:

Explicitly start a particular Service or Activity using its class name

Start an Activity or Service to perform an action with (or on) a particular piece of
data

Broadcast that an event has occurred

UHD-CST Karzan H. Sharif

Intents

Primary Application Components


1. Activity
Single screen with a user interface, application may have several activities which are
subclasses of Activity

2. Service
Application component that performs long running operations in background with no UI

3. Content Providers
A bridge between applications to share data

4. Broadcast Receivers : Component that responds to system wide announcements

UHD-CST Karzan H. Sharif

Using Intents to Launch Activities


Intents are used to start Activities, allowing you to create a workow of
different screens.
The startActivity method nds and starts the single Activity that best
matches your Intent
Intent myintent = new Intent(MyActivity.this, MyOtherActivity.class);
To create and display an Activity, call startActivity, passing in an Intent, as
follows:
startActivity(myIntent);

UHD-CST Karzan H. Sharif

10

AndroidManifest.xml file
Every application must have an AndroidManifest.xml file in its root directory
The manifest contains important data about the application that is required by the

Android system before the system will run any of the application's code

Declare this as Activity to start


when application started

11

Purpose of AndroidManifest.xml
There are several purposes of the AndroidManifest.xml:
Contains Java package name of application - unique ID for application
Describes components of application, such as Activities, Services, Broadcast
Receivers, Content Providers and intent messages each component can handle

Declares permissions requested by application


Minimum required API level
Libraries application to link to

UHD-CST Karzan H. Sharif

12

Intent Class and Objects


Intents are objects of the android.content.Intent type, your code can send
them to the Android system defining the components you are targeting
Passive data structure

Description of action to performed or if created by a broadcast, a description of

something that has happened and is being announced to broadcast receivers

Intent objects carry information, but do not perform any actions themselves

UHD-CST Karzan H. Sharif

13

Intents and App Components


Intent to Launch Activity or
change purpose of existing
Activity

Intent to Initiate Service


or give new instructions
to existing Service
Intents intended for
Broadcast Receivers

Context.startActivity()
Activity.startActivityForResult()
Activity.setResult()
Context.startService()
Context.bindService()
Context.sendBroadcast()
Context.sendOrderedBroadcast()
Context.sendStickyBroadcast()

The Android System finds the right application component to respond to intents,
instantiating them if necessary
UHD-CST Karzan H. Sharif

14

Intent Object Information


An Intent Object contains information of interest to the component that
receives the intent (e.g. the action to be taken and the data to act on) plus
information interest to the Android system

UHD-CST Karzan H. Sharif

15

Intent Object Information (2)


Intent Object contains the following:

1. Component name: The name of the component to start. This is optional,


but it's the critical piece of information that makes an intent explicit.
Without a component name, the intent is implicit and the system decides
which component should receive the intent based on the other intent
information (such as the action, data, and categorydescribed later)..
Note: When starting a Service, always specify the component name.
Otherwise, you cannot be certain what service will respond to the intent, and
the user cannot see which service starts.
For example, com.example.ExampleActivity.

UHD-CST Karzan H. Sharif

16

Intent Object Information (3)


You can set the component name with setComponent(),
setClassName() or with the Intent constructor.
An example is the MapsActivity in the Google Maps
application:
intent.setComponent(new ComponentName
("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity"));

UHD-CST Karzan H. Sharif

17

Intent Object Information (4)


2. Action: This piece of information names the action an Android
component should take on receiving the Intent, and is being notified to
the system.

Action acts like a method name

Determines what rest of data in Intent is and how it is structured,


especially the data and extras.
setAction() is used to set Action, and getAction() is used to read Action
The Android system defines a number of Action Constants. We have listed
in the next slide:
UHD-CST Karzan H. Sharif

18

Intent Object Information (5)


Intent Action

19

Intent Object Information (6)


3. Data: Contains the Uniform Resource Identifier (URI) of the data.
If the action defined were ACTION_CALL, the data field would contain a
number to call (tel: URI).
For correctly matching Intent to a suitable component, defining the data
type (in addition to the URI) helps. For instance, a component to display
image should be called to display image only, not to play an audio file.

UHD-CST Karzan H. Sharif

20

Intent Object Information (7)


4. Category: A string containing additional information about the kind of
component that should handle the intent.
Any number of category descriptions can be placed in an intent, but most
intents do not require a category.
Here are some common categories:
CATEGORY_BROWSABLE The target activity allows itself to be started by a
web browser to display data referenced by a link, such as an image or an
e-mail message.
CATEGORY_LAUNCHER The activity is the initial activity of a task and is
listed in the system's application launcher.
UHD-CST Karzan H. Sharif

21

Intent Object Information (8)


Intent class defines several category constants:

22

Intent Object Information (9)


5. Extras
Additional information that should be given to the component handling
the Intent

Some Actions will have specified extras:

e.g. ACTION_TIMEZONE_CHANGED will have an extra with key of time


zone that identifies the new time zone

In fact, the extras can be installed using the putExtras() and getExtras()
methods

UHD-CST Karzan H. Sharif

23

Intent Object Information (10)


6. Flags
To help control how Intent is handled
Many instruct the Android system:
how to launch an activity?

e.g. which task the activity should belong to

how to treat it after it is launched?

e.g. whether it belongs in the list of recent activities

All the flags are defined in the Intent class


For more information, see the setFlags() method.
https://developer.android.com/reference/android/content/Intent.html#setFlags(int)
UHD-CST Karzan H. Sharif

24

Intent Types
Intent can be divided into two groups:
1. Explicit Intent

specifies the component which should be called by the Android system, usually using

the Java class identifier

the following code shows how to create an explicit intents and send it to Android
system:
Intent explicitIntent = new Intent(this, ActivityClass.class);

UHD-CST Karzan H. Sharif

25

Intent Types (2)


2. Implicit Intent

specifies the action which should be performed and optionally data that provides data for

the action

do not specify the exact Java class to be called

the following code tells the Android system to view a webpage:

Intent implicitIntent = new Intent(Intent.ACTION_VIEW,


URI.parse(http://www.google.com));
startActivity(implicitIntent );
UHD-CST Karzan H. Sharif

26

UHD-CST Karzan H. Sharif

27

Intent Filter
Applications and components that can receive Implicit Intents advertise what they can
do through Intent Filters

Components with no Intent Filter can only receive Explicit Intents

typically of many activities

Activities, Services and Broadcast Receivers can have one or more Intent Filters

Intent Filters generally declared as element of applications in the


AndroidManifest.xml file
Intent Filter must contain at least one <action> element

UHD-CST Karzan H. Sharif

28

Intent Filter (2)


The Android system populates the application launcher via Intent Filter

UHD-CST Karzan H. Sharif

29

Explicit Intent Example

UHD-CST Karzan H. Sharif

30

Explicit Intent Example (2)


The applications AndroidManifest.xml file

UHD-CST Karzan H. Sharif

31

Implicit Intent Example

UHD-CST Karzan H. Sharif

32

Implicit Intent Example (2)


The applications AndroidManifest.xml file

UHD-CST Karzan H. Sharif

33

Creating another Activity


There are several steps which can be used to create another activity:

First Step: the requesting activity creates an Intent object and provides it

with the required information e.g. component name, data, action, .. etc

Second Step: the requesting activity launches the new activity by


startActivity(Intent), starting new activity with no expected result

UHD-CST Karzan H. Sharif

34

Data transfer to the target component

PutExtar & getExtra, For example to get some information like name, surname,
email when user login on Android, and show on second activity these information ,
we can use getExtra and putExtra .

startActivityForResult(Intent, int), starting a new activity to get a result back from


the receiving activity when it ends. The second integer parameter is used to identify

the call

The result will come back through a callback method onActivityResult(int, int,
Intent)
UHD-CST Karzan H. Sharif

35

Passing Extra Example

36

Passing Extra Example

37

Passing Extra Example

38

For Result Example

39

For Result Example

40

For Result Example

41

Broadcast receiver
Broadcast Receivers simply respond to broadcast messages from
other applications or from the system itself.
These messages are sometime called events or intents.
For example, applications can also initiate broadcasts to let other
applications know that some data has been downloaded to the
device and is available for them to use, so this is broadcast
receiver who will intercept this communication and will initiate
appropriate action.
UHD-CST Karzan H. Sharif

42

Broadcast receiver(2)
There are following two important steps to make Broadcast
Receiver works for the system broadcasted intents
Creating the Broadcast Receiver.
Registering Broadcast Receiver

UHD-CST Karzan H. Sharif

43

Creating the Broadcast Receiver


A broadcast receiver is implemented as a subclass of Broadcast
Receiver class and overriding the onReceive() method where
each message is received as a Intent object parameter.
public class MyReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show(); }
}
UHD-CST Karzan H. Sharif

44

Registering Broadcast Receiver


An application listens for specific broadcast intents by
registering a broadcast receiver in AndroidManifest.xml
file.
There are several system generated events defined as
final static fields in the Intent class. The following table
lists a few important system events.
UHD-CST Karzan H. Sharif

45

Important system events

46

Broadcasting Custom Intents


If you want your application itself should generate and send
custom intents then you will have to create and send those
intents by using the sendBroadcast() method inside your
activity class.
public void broadcastIntent(View view) {
Intent intent = new Intent();
intent.setAction("com.example.karzan.A_CUSTOM_INTENT ");
sendBroadcast(intent); }
UHD-CST Karzan H. Sharif

47

Broadcasting Custom Intents(2)


This intent com.example.karzan.A_CUSTOM_INTENT can
also be registered in similar way as we have regsitered system
generated intent.
<receiver
android:name="MyReceiver">
<intent-filter>
<action android:name=" com.example.karzan.A_CUSTOM_INTENT ">
</action>
</intent-filter>
</receiver>

UHD-CST Karzan H. Sharif

48

Practice

49

Insert this method into MainActivity class file


public void broadcastCustomIntent(View view)
{
Intent intent = new Intent("MyCustomIntent");

EditText et = (EditText)findViewById(R.id.extraIntent);
// add data to the Intent
intent.putExtra("message", (CharSequence)et.getText().toString());

intent.setAction("com.example.karzan.A_CUSTOM_INTENT");
sendBroadcast(intent);
}

UHD-CST Karzan H. Sharif

50

Create MyBroadcastReceiver Class

51

Insert this code into Manifest file

UHD-CST Karzan H. Sharif

52

UHD-CST Karzan H. Sharif

53

UHD-CST Karzan H. Sharif

54

Você também pode gostar