The document discusses intents, broadcast receivers, and intent filters in Android. It provides examples of explicit intents that specify a component directly and implicit intents that declare an action without specifying a component. Implicit intents can be received by components that declare intent filters supporting the action, MIME type, and category. The document also discusses using intent filters in the app manifest to advertise which implicit intents an app's activities, services, and broadcast receivers can receive.
1 of 85
Downloaded 34 times
More Related Content
Tk2323 lecture 3 intent
1. Intent and broadcast receiver
TK2323 Mobile Programming
Sem 1 2017/2018
Lam Meng Chun
lammc@ukm.edu.my (H-04-10)
4. Event Listeners
An event listener is an
interface in the View
class that contains a
single callback method.
These methods will be
called by the Android
framework when the
View to which the
listener has been
registered is triggered
by user interaction with
the item in the UI.
4
5. Event Listeners
onClick()
From View.OnClickListener. This is called when the user
either touches the item (when in touch mode), or
focuses upon the item with the navigation-keys or
trackball and presses the suitable "enter" key or presses
down on the trackball.
5
6. Event Listeners
onLongClick()
From View.OnLongClickListener. This is called when the
user either touches and holds the item (when in touch
mode), or focuses upon the item with the navigation-keys
or trackball and presses and holds the suitable "enter"
key or presses and holds down on the trackball (for one
second).
6
11. 11
Intent
An Intent is a messaging object
you can use to request an
action from another app
component.
11
12. Intent
Although intents facilitate communication between
components in several ways, there are three fundamental
use-cases:
To start an activity
皙startActivity(intent);
To start a service
皙startService(intent);
To deliver a broadcast
皙sendBroadcast(intent);
12
13. Android App
Components(Activities)
An Activity is an application
component that provides a
screen with which users can
interact in order to do
something, such as dial the
phone, take a photo, send an
email, or view a map.
Each activity is given a window
in which to draw its user
interface. The window typically
fills the screen, but may be
smaller than the screen and
float on top of other windows.
13
14. Android App
Components(Services)
A Service is an
application
component that can
perform long-
running operations
in the background
and does not
provide a user
interface.
Another application
component can start
a service and it will
continue to run in
the background even
if the user switches
to another
application
For example, a
service might handle
network
transactions, play
music, perform file
I/O, or interact with a
content provider, all
from the
background.
14
15. Android App
Components(Services)
startService()
service can run in the background indefinitely, even if
the component that started it is destroyed.
Usually, a started service performs a single operation
and does not return a result to the caller.
For example, it might download or upload a file over
the network. When the operation is done, the service
should stop itself.
15
http://developer.android.com/guide/components/services.html
16. Android App
Components(Services)
bindService()
A service is "bound" when an application component
binds to it by calling bindService().
A bound service offers a client-server interface that
allows components to interact with the service, send
requests, get results, and even do so across processes
with interprocess communication (IPC).
16
http://developer.android.com/guide/components/services.html
17. Android App
Components(Services)
bindService()
A bound service runs only as long as another
application component is bound to it. Multiple
components can bind to the service at once, but when all
of them unbind, the service is destroyed.
17
http://developer.android.com/guide/components/services.html
18. Android App
Components(Broadcast
Receivers)
A broadcast receiver is
a component that
responds to system-
wide broadcast
announcements.
Many broadcasts
originate from the
systemfor example, a
broadcast announcing
that the screen has
turned off, the battery is
low, or a picture was
captured.
18
19. Android App Components
(Intents)
Explicit Intents
specify the component to
start by name (the fully-
qualified class name).
You'll typically use an explicit
intent to start a component in
your own app, because you
know the class name of the
activity or service you want to
start.
Implicit Intents
do not name a specific
component, but instead declare
a general action to perform,
which allows a component from
another app to handle it.
For example, if you want to
show the user a location on a
map, you can use an implicit
intent to request that another
capable app show a specified
location on a map
19
24. Implict Intent
24
[1] Activity A creates an Intent with an action description and passes it
to startActivity().
[2] The Android System searches all apps for an intent filter that
matches the intent. When a match is found,
[3] the system starts the matching activity (Activity B) by invoking its
onCreate() method and passing it the Intent.
25. Implicit Intent
Action
A string that
specifies the generic
action to perform
(such as view or
pick).
ACTION_INSERT
ACTION_DIAL
ACTION_VIEW
ACTION_EDIT
ACTION_SEND
Data
The URI (a Uri object)
that references the
data to be acted on
and/or the MIME type
of that data.
"text/plain
"image/jpeg"
"image/bmp"
"image/png
"video/wav"
"video/mp4"
Extras
Key-value pairs that
carry additional
information
required to
accomplish the
requested action.
Just as some actions
use particular kinds
of data URIs, some
actions also use
particular extras.
25
26. Implicit
Intent Make a
phone call
26
Uri number = Uri.parse("tel:0124584125");
Intent callIntent =
new Intent(Intent.ACTION_DIAL, number);
startActivity (callIntent);
27. 2727
// Map point based on address
Uri location =
Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California"
);
// Or map point based on latitude/longitude
// Uri location = Uri.parse("geo:37.422219,-122.08364?z=14"); // z param
is zoom level
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
Implicit Intent (View a map:)
28. Implicit Intent (View a Webpage:)28
Uri webpage = Uri.parse("http://www.google.com");
Intent webIntent =
new Intent(Intent.ACTION_VIEW, webpage);
startActivity (webIntent);
29. Implicit Intent (Send email)
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// The intent does not have a URI, so declare the "text/plain" MIME type
emailIntent.setType(HTTP.PLAIN_TEXT_TYPE);
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]
{"jon@example.com"}); // recipients
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text");
emailIntent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("content://path/to/email/attachment"));
29
30. Implicit Intent (Send email)
Verify There is an App to Receive the Intent
// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities =
packageManager.queryIntentActivities(mapIntent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it has app to handle the intent
if (isIntentSafe) {
startActivity(mapIntent);
}
30
31. Implicit Intent (App Chooser)
If the action to be performed
could be handled by multiple
apps and the user might prefer
a different app each time
such as a "share" action, for
which users might have several
apps through which they might
share an item
you should explicitly show a
chooser dialog
The chooser dialog forces the
user to select which app to use
for the action every time (the
user cannot select a default
app for the action).
31
34. Receiving an Implicit Intent
(Intent-filter)
To advertise/accept which implicit intents your app can
receive, declare one or more intent filters for each of your
app components with an <intent-filter> element in your
manifest file.
handle such an implicit intent where we take an HTTP URL
and do some useful jazz with it
34
35. Receiving an Implicit Intent
(Intent-filter)
In such a case Android will give two choices to the user
default installed browser (chrome) and our app from
which he can make a selection
To register a component of our app that can receive an
implicit intent for a specific action and data, we can declare
an <intent-filter> for that particular component (activity,
service or a broadcast receiver) in our manifest file.
35
36. Receiving an Implicit Intent
(Intent-filter)
<action>
Declares the intent action accepted, in the name
attribute. The value must be the literal string value of an
action, not the class constant.
36
37. Receiving an Implicit Intent
(Intent-filter)
<data>
Declares the type of data accepted, using one or more
attributes that specify various aspects of the data URI
(scheme, host, port, path, etc.) and MIME type.
37
38. Receiving an Implicit Intent
(Intent-filter)
<category>
Declares the intent category accepted, in the name
attribute. The value must be the literal string value of an
action, not the class constant.
In order to receive implicit intents, you must include
the CATEGORY_DEFAULT category in the intent filter. If
you do not declare this category in your intent filter, no
implicit intents will resolve to your activity.
38
40. Receiving an Implicit Intent
(Intent-filter)
The first activity, MainActivity, is the app's main entry pointthe
activity that opens when the user initially launches the app with the
launcher icon:
The ACTION_MAIN action indicates this is the main entry point and
does not expect any intent data.
The CATEGORY_LAUNCHER category indicates that this activity's
icon should be placed in the system's app launcher. If
the <activity> element does not specify an icon with icon, then the
system uses the icon from the <application> element.
These two must be paired together in order for the activity to appear
in the app launcher.
40
41. Receiving an Implicit Intent
(Intent-filter)
The second activity, ShareActivity, is intended to facilitate
sharing text and media content.
Although users might enter this activity by navigating to it
from MainActivity,
they can also enter ShareActivity directly from another
app that issues an implicit intent matching one of the two
intent filters.
41
42. Common Implicit Intent
Alarm Clock
Calendar
Camera
Contacts/People App
Email
File Storage
Local Actions Maps
Music or Video Phone
Search Settings
Text Messaging
Web Browser
Verify Intents with the
Android Debug Bridge
Intents Fired by Google Now
42
https://developer.android.com/guide/components/intents-common.html
47. Activity-
LifeCycle
47
Method Purpose
onCreate() The activity is being created..
Used to initialize the activity/UI.
For example create the user interface
onStart() The activity is about to become visible.
onResume() Called if the activity get visible again and the user starts to interacting
with the activity again.
Used to initialize fields, register listeners, bind to service, etc.
onPause() Called once another activity gets into the foreground. Always called
before the activity is not visible anymore.
Used to release resources or save application data. For example you
unregister listeners, intent receiver, unbind from services or remove
system service listeners.
onStop() Called once the activity is no longer visible. Time or CPU intensive shut
down operation, such as writing information to database should be down
in the onStop() method.
onDestroy() The activity is about to be destroyed.
you should kill long-running resources that could potentially leak
memory
48. Activity-LifeCycle
Why need to understand activity life cycle
Does not crash if the user receives a phone call or
switches to another app while using your app.
Does not consume valuable system resources when the
user is not actively using it.
Does not lose the user's progress if they leave your app
and return to it at a later time.
Does not crash or lose the user's progress when the
screen rotates between landscape and portrait
orientation.
48
http://developer.android.com/training/basics/
activity-lifecycle/starting.html
50. ToolBar
A Toolbar is a generalization of action bars for use within application
layouts.
While an action bar is traditionally part of an Activity's opaque window
decor controlled by the framework, a Toolbar may be placed at any
arbitrary level of nesting within a view hierarchy.
Its a generalization of the Action Bar that isnt bound to an Activitys
window decor, can be placed anywhere in the user interface.
Its highly customizable, which means you can add navigation
buttons, branded logos, titles, subtitle, action menu items, or even your
own custom views.
50
54. ToolBar
54
The nav icon at the left side of the app bar can be:
A control to open a navigation drawer.
An up arrow for navigating upward through your apps
hierarchy.
Omitted entirely if no navigation is required from this
screen.
55. AppBar
55
The title in the app bar reflects the current page.
It can be an app title, page title, or a page filter.
Action Icons on the right side of the app bar are app-related
actions.
The menu icon opens the overflow menu, which contains
secondary actions and menu items like help, settings, and
feedback.
57. OUR PROCESS IS EASY57
Remove action bar
from the app theme
Add Toolbar view to xml
layout file
Link Toolbar in activity
java file
Create menu resource
Add menu and click
event in activity java
58. Remove
action bar
from the app
theme
58
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
60. Link Toolbar
in activity
java file
60
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupToolbar();
}
private void setupToolbar()
{
//get the toolbar from the xml file
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// tell the "AppCompatActivity" use this toolbar
setSupportActionBar(toolbar);
// get the actionbar/appbar from the "AppCompatActivity"
final ActionBar myActionBar = getSupportActionBar();
myActionBar.setDisplayHomeAsUpEnabled(true);
}
62. Add menu
and click
event in
activity java
62
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//it is a "tool" that generate the UI from the menu resources
MenuInflater inflater = getMenuInflater();
//define which menu wanted to generated
inflater.inflate(R.menu.menu_main,menu);
return true;
}
To specify the options menu for an activity, override onCreateOptionsMenu() (fragments
provide their own onCreateOptionsMenu() callback). In this method, you can inflate your
menu resource (defined in XML) into the Menu provided in the callback.
63. Add menu and
click event in
activity java (
Continue)
63
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//click event for the menu's item
switch (item.getItemId())
{
case R.id.action_menu_search:
Toast.makeText(getApplicationContext(),"Search Clicked",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this,Search.class);
startActivity(intent);
return true;
case R.id.action_menu_sync:
Toast.makeText(getApplicationContext(),"Sync Clicked",Toast.LENGTH_SHORT).show();
intent = new Intent(this,Sync.class);
startActivity(intent);
return true;
case R.id.action_menu_settings:
Toast.makeText(getApplicationContext(),"Settings Clicked",Toast.LENGTH_SHORT).show();
intent = new Intent(this,settings.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
64. Your Task
Finish your lab 1
Show it during the lab hour then mark will be given
Upload to ifolio in the Tasks section
Lab Test
64
66. Broadcast Receivers
Imagine an event like external power being
connected/disconnected from the device, screen turning
on/off, battery getting low or picture captured.
All these events originate from the system.
66
67. Broadcast Receivers
Apps can also initiate broadcastsfor example, to let
other apps know that some data has been downloaded to
the device and is available for them to use.
In fact apps themselves can also initiate broadcasts for
example the SMS app broadcasting that an SMS has being
received and let other apps know about this event so
that they can trigger some action
67
68. Broadcast Receivers
Although broadcast receivers don't display a user
interface, they may create a status bar notification to alert
the user when a broadcast event occurs.
68
69. Broadcast Receivers
More commonly, though, a broadcast receiver is just a
"gateway" to other components and is intended to do a very
minimal amount of work.
For instance, it might initiate a service to perform some
work based on the event.
69
73. Step to make broadcast
works
There are following two important steps to make
Broadcast Receiver works for the system broadcasted
intents:
Creating the Broadcast Receiver
皙extends BroadcastReceiver
Registering Broadcast Receiver
皙register a BroadcastReceiver in manifest
73
74. Creating the Broadcast
Receiver
public class BatteryLevelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BATTERY_LOW")) {
Toast.makeText(context, "Battery Low", Toast.LENGTH_LONG).show();
// Stop downloading or other heavy process.
} else if (intent.getAction().equals(
"android.intent.action.BATTERY_OKAY")) {
Toast.makeText(context, "Battery Okay", Toast.LENGTH_LONG).show();
}
}
}
74
78. Step to make custom
broadcast works
There are following two important steps to make
Broadcast Receiver works for the system broadcasted
intents:
Creating the Broadcast Receiver.
Registering Broadcast Receiver
Send the Broadcast
78
79. Broadcast Receiver: Creating
the Broadcast Receiver
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, Broadcast Detected."+intent.getPackage(),
Toast.LENGTH_LONG).show();
}
}
79
80. Broadcast Receiver: Registering
the Broadcast Receiver
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="com.tk2323.sendBroadCast" />
</intent-filter>
</receiver>
80
Registering a broadcast receiver in AndroidManifest.xml
Created an IntentFilter object that specifies which event/intent our
receiver will listen to.
81. Broadcast Receiver: Send the
Broadcast Receiver
btnBroadcast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction("com.tk2323.sendBroadCast");
sendBroadcast(intent);
}
});
81