SlideShare a Scribd company logo
1 of 85
Intent and broadcast receiver
TK2323 Mobile Programming
Sem 1 2017/2018
Lam Meng Chun
lammc@ukm.edu.my (H-04-10)
Outline
Activity Life Cycle
Intent
▹Explicit
▹Implicit
Toolbar
2
Intent Filter and
Resolution
Event Listener Toast
Broadcast Receiver
▸Optional
Event Listener
3
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
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
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
Button On
Click Event
7
Toast
8
Toast
Toast.makeText(getApplicationContext(),
"Agree is clicked",
Toast.LENGTH_SHORT).show();
9
Intent
10
11
Intent
An Intent is a messaging object
you can use to request an
action from another app
component.
11
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
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
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
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
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
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
Android App
Components(Broadcast
Receivers)
▹A broadcast receiver is
a component that
responds to system-
wide broadcast
announcements.
▹Many broadcasts
originate from the
system—for example, a
broadcast announcing
that the screen has
turned off, the battery is
low, or a picture was
captured.
18
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
Explicit Intent
20
Explicit Intent (Example)
Intent i = new Intent(MainActivity.this,
ActivityB.class);
startActivity(i);
21
Explicit Intent (Example)
Intent downloadIntent = new
Intent(MainActivity.this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);
22
Implicit Intent
23
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.
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
Implicit
Intent Make a
phone call
26
Uri number = Uri.parse("tel:0124584125");
Intent callIntent =
new Intent(Intent.ACTION_DIAL, number);
startActivity (callIntent);
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:)
Implicit Intent (View a Webpage:)28
Uri webpage = Uri.parse("http://www.google.com");
Intent webIntent =
new Intent(Intent.ACTION_VIEW, webpage);
startActivity (webIntent);
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
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
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
App Chooser
32
Intent Filter
33
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
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
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
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
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
Receiving an
Implicit
Intent
(Intent-filter)
39
Receiving an Implicit Intent
(Intent-filter)
▹The first activity, MainActivity, is the app's main entry point—the
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
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
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
Intent Filter –
Example Handle
Text Message
43
Activity-Life Cycle
44
Android
Activity-
LifeCycle
45
Android
Activity-
LifeCycle
46
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
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
Toolbar/AppBar
(ActionBar)
An action bar that includes the [1] app icon, [2] two action items, and [3] action
overflow.
49
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.
▹It’s a generalization of the Action Bar that isn’t bound to an Activity’s
window decor, can be placed anywhere in the user interface.
▹It’s highly customizable, which means you can add navigation
buttons, branded logos, titles, subtitle, action menu items, or even your
own custom views.
50
ToolBar
Full-width, default
height app bar
Full-width, extended
height app bar
Column-width toolbars
at multiple levels of
hierarchy
51
ToolBar
Flexible toolbar and
card toolbar
Floating toolbar
52
ToolBar
53
▹Bottom toolbar that
launches to a shelf and
clings to the top of the
keyboard or other
bottom component
▹Bottom toolbar shelf
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 app’s
hierarchy.
▸Omitted entirely if no navigation is required from this
screen.
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.
Step to Create App Bar
56
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
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>
Add Toolbar
view to xml
layout file
59
<?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"
tools:context="com.ta2323.ftsm.lab_appbar_a111111.MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/> </RelativeLayout>
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);
}
Create menu
resource
61
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_menu_search"
android:orderInCategory="1"
android:title="@string/search"
android:icon="@drawable/ic_action_search"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_menu_sync"
android:orderInCategory="2"
android:title="@string/sync"
android:icon="@drawable/ic_sync"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_menu_settings"
android:orderInCategory="3"
android:icon="@drawable/ic_settings"
android:title="@string/settings"
app:showAsAction="never" />
</menu>
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.
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);
}
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
Broadcast receiver
(Optional)
65
A broadcast receiver is a component that responds
to system-wide broadcast announcements.
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
Broadcast Receivers
▹Apps can also initiate broadcasts—for 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
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
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
Broadcast Receivers70
Broadcast Receivers71
Broadcast receiver
(Battery)
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
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
Registering Broadcast
Receiver
<receiver android:name=".BatteryLevelReceiver" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW" />
<action android:name="android.intent.action.BATTERY_OKAY" />
</intent-filter>
</receiver>
75
Custom Broadcast
receiver
7777
Broadcast Receivers
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
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
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.
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
Broadcast receiver
with message
(Notification)
Broadcast Receiver: Seding
the Broadcast Receiver
btnBroadcastMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, MessageReceiver.class);
intent.putExtra("message","Wake up.");
sendBroadcast(intent);
}
});
83
Broadcast Receiver: Registering
the Broadcast Receiver
▹Registering a broadcast receiver in AndroidManifest.xml
<receiver android:name="MessageReceiver"/>
84
Broadcast Receiver: Creating
Broadcast Receiver
public void onReceive(Context context, Intent intent) {
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon_notification)
.setContentTitle("My notification")
.setContentText(intent.getStringExtra("message"));
NotificationManager mNotifyMgr =(NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, mBuilder.build());
}
85
http://developer.android.com/training/notify-user/index.html

More Related Content

Similar to Tk2323 lecture 3 intent

android_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semandroid_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last sem
aswinbiju1652
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; Share
Anuchit Chalothorn
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
Utkarsh Mankad
 

Similar to Tk2323 lecture 3 intent (20)

Level 1 &amp; 2
Level 1 &amp; 2Level 1 &amp; 2
Level 1 &amp; 2
 
Android intents in android application-chapter7
Android intents in android application-chapter7Android intents in android application-chapter7
Android intents in android application-chapter7
 
android_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semandroid_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last sem
 
Android - Android Intent Types
Android - Android Intent TypesAndroid - Android Intent Types
Android - Android Intent Types
 
Android development session 2 - intent and activity
Android development   session 2 - intent and activityAndroid development   session 2 - intent and activity
Android development session 2 - intent and activity
 
unit3.pptx
unit3.pptxunit3.pptx
unit3.pptx
 
Android Intent.pptx
Android Intent.pptxAndroid Intent.pptx
Android Intent.pptx
 
Tut123456.pdf
Tut123456.pdfTut123456.pdf
Tut123456.pdf
 
Intent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).pptIntent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).ppt
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; Share
 
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Pertemuan 03 - Activities and intents.pptx
Pertemuan 03 - Activities and intents.pptxPertemuan 03 - Activities and intents.pptx
Pertemuan 03 - Activities and intents.pptx
 
Android Studio Tutorial For Beginners -2 | Android Development Tutorial | And...
Android Studio Tutorial For Beginners -2 | Android Development Tutorial | And...Android Studio Tutorial For Beginners -2 | Android Development Tutorial | And...
Android Studio Tutorial For Beginners -2 | Android Development Tutorial | And...
 
Intents are Awesome
Intents are AwesomeIntents are Awesome
Intents are Awesome
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
MAD-Lec8 Spinner Adapater and Intents (1).ppt
MAD-Lec8 Spinner Adapater and Intents (1).pptMAD-Lec8 Spinner Adapater and Intents (1).ppt
MAD-Lec8 Spinner Adapater and Intents (1).ppt
 
Android Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intentsAndroid Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intents
 

More from MengChun Lam (10)

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensor
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api json
 
Tk2323 lecture 11 process and thread
Tk2323 lecture 11   process and threadTk2323 lecture 11   process and thread
Tk2323 lecture 11 process and thread
 
Tk2323 lecture 8 firebase
Tk2323 lecture 8   firebaseTk2323 lecture 8   firebase
Tk2323 lecture 8 firebase
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui ux
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler view
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 ui
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile application
 

Recently uploaded

Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Cara Menggugurkan Kandungan 087776558899
 

Recently uploaded (6)

Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 

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)
  • 2. Outline Activity Life Cycle Intent ▹Explicit ▹Implicit Toolbar 2 Intent Filter and Resolution Event Listener Toast Broadcast Receiver ▸Optional
  • 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 system—for 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
  • 21. Explicit Intent (Example) Intent i = new Intent(MainActivity.this, ActivityB.class); startActivity(i); 21
  • 22. Explicit Intent (Example) Intent downloadIntent = new Intent(MainActivity.this, DownloadService.class); downloadIntent.setData(Uri.parse(fileUrl)); startService(downloadIntent); 22
  • 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 point—the 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
  • 43. Intent Filter – Example Handle Text Message 43
  • 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
  • 49. Toolbar/AppBar (ActionBar) An action bar that includes the [1] app icon, [2] two action items, and [3] action overflow. 49
  • 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. ▹It’s a generalization of the Action Bar that isn’t bound to an Activity’s window decor, can be placed anywhere in the user interface. ▹It’s highly customizable, which means you can add navigation buttons, branded logos, titles, subtitle, action menu items, or even your own custom views. 50
  • 51. ToolBar Full-width, default height app bar Full-width, extended height app bar Column-width toolbars at multiple levels of hierarchy 51
  • 52. ToolBar Flexible toolbar and card toolbar Floating toolbar 52
  • 53. ToolBar 53 ▹Bottom toolbar that launches to a shelf and clings to the top of the keyboard or other bottom component ▹Bottom toolbar shelf
  • 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 app’s 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.
  • 56. Step to Create App Bar 56
  • 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>
  • 59. Add Toolbar view to xml layout file 59 <?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" tools:context="com.ta2323.ftsm.lab_appbar_a111111.MainActivity"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" /> </RelativeLayout>
  • 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); }
  • 61. Create menu resource 61 <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_menu_search" android:orderInCategory="1" android:title="@string/search" android:icon="@drawable/ic_action_search" app:showAsAction="ifRoom" /> <item android:id="@+id/action_menu_sync" android:orderInCategory="2" android:title="@string/sync" android:icon="@drawable/ic_sync" app:showAsAction="ifRoom" /> <item android:id="@+id/action_menu_settings" android:orderInCategory="3" android:icon="@drawable/ic_settings" android:title="@string/settings" app:showAsAction="never" /> </menu>
  • 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
  • 65. Broadcast receiver (Optional) 65 A broadcast receiver is a component that responds to system-wide broadcast announcements.
  • 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 broadcasts—for 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
  • 75. Registering Broadcast Receiver <receiver android:name=".BatteryLevelReceiver" > <intent-filter> <action android:name="android.intent.action.BATTERY_LOW" /> <action android:name="android.intent.action.BATTERY_OKAY" /> </intent-filter> </receiver> 75
  • 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
  • 83. Broadcast Receiver: Seding the Broadcast Receiver btnBroadcastMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this, MessageReceiver.class); intent.putExtra("message","Wake up."); sendBroadcast(intent); } }); 83
  • 84. Broadcast Receiver: Registering the Broadcast Receiver ▹Registering a broadcast receiver in AndroidManifest.xml <receiver android:name="MessageReceiver"/> 84
  • 85. Broadcast Receiver: Creating Broadcast Receiver public void onReceive(Context context, Intent intent) { new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.icon_notification) .setContentTitle("My notification") .setContentText(intent.getStringExtra("message")); NotificationManager mNotifyMgr =(NotificationManager)context .getSystemService(Context.NOTIFICATION_SERVICE); mNotifyMgr.notify(001, mBuilder.build()); } 85 http://developer.android.com/training/notify-user/index.html