Mobile Application Development
(Intent, Service and BroadcastReciver)
Agenda
1. Intent and filter
– An overview of Intent
– Types of Intent
– Building Intent object
– Intent Filters
2. Android: Service
– An overview of Service
– State of Service
– Life cycle of Service
– Implementation of Service
3. BroadcastReciever
Intent and Filter
An overview of Intent
• Intents are asynchronous messages which allow application
components to request functionality from other Android
components.
• i.e. An Intent is a messaging object you can use to request an
action from another application component.
• An Android Intent is an abstract description of an operation to
be performed.
• Intents allow you to interact with components from the same
applications as well as with components contributed by other
applications.
Cont . . .
• Intents are objects of the android.content.Intent type.
• Your code can send them to the Android system defining the
components you are targeting.
• Intents facilitate communication between components in
several ways, and there are separate mechanisms for delivering
intents to each type of component − activities, services, and
broadcast receivers.
A) Starting an activity
– You can start a new instance of an Activity by passing an
Intent object to startActivity() method.
– The Intent object describes the activity to start and carries
any necessary data.
Cont . . .
B) Starting a service
– You can start a service to perform a one-time operation (such
as downloading a file) by passing an Intent object to
startService() method.
– With Android 5.0 (API level 21) and later, you can also start a
service with JobScheduler.
– The Intent object describes the service to start and carries
any necessary data.
– If the service is designed with a client-server interface, you
can bind to the service from another component by passing
an Intent object to bindService() method.
Cont . . .
C) Delivering a broadcast
– The system delivers various broadcasts for system events,
such as when a system boots up or the device starts charging.
– You can deliver a broadcast to other applications by passing
Intent object to sendBroadcast() or sendOrderedBroadcast()
method.
• Example: How to use intent object to start Activity and Services
as well as to deliver Broadcast
Intent myIntent = new Intent(this, TargetActivity.class);
startActivity(myIntent);
startService(myIntent);
sendBroadcast(myIntent);
Types of Intent
• There are following two types of intents supported by Android
A) Explicit Intents
– It going to be connected internal world of application,
– 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.
– E.g., you can start a new activity in response to a user action
or start a service to download a file in the background.
Cont . . .
B) Implicit Intents
– It going to be connected external world of application,
– Do not name a specific component, but instead declare a
general action to perform, which allows a component from
another app to handle it.
– E.g., if you want to show the user location on a map, you can
use an implicit intent to request that another capable app
show a specified location on a map.
– The Figure below show how an implicit intent is delivered
through the system to start another activity
Cont . . .
Example of explicit and implicit intent
– Explicit intent
– Implicit intent – the following code tell the Android system
to view a webpage
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
startActivity(i);
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.vogella.com"));
startActivity(i);
Building an intent object
• An Intent object carries information that the Android system
uses to determine which component to start (such as the exact
component name or component category that should receive
the intent), plus information that the recipient component uses
in order to properly perform the action (such as the action to
take and the data to act upon).
• The primary information contained in an Intent is the following:
– Component name
– Action
– Data
– Category
– Extras
– Flags
Cont . . .
• Component name
– Represents android component such as Activity, Service or
BroadcastReceiver class.
– If you need to start a specific component in your app, you should
specify the component name, to makes an intent explicit, meaning
that the intent should be delivered only to appn component
defined by the component name.
– Without component name, intent is implicit and the system
decides which component should receive the intent based on the
other intent information (such as action, data, and category which
will explained later in this section).
– 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.
– The component name is set by setComponent(), setClass(), or
setClassName() or with the Intent constructor and read by
getComponent().
Cont . . .
• Action
– It is mandatory element of of the Intent object
– A string that specifies a generic action to perform (such as view
or pick).
– In the case of a broadcast intent, this is the action that took
place and is being reported.
– The action largely determines how the rest of the intent is
structured particularly the information that is contained in the
data and extras.
– You can specify your own actions for use by intents within your
app (or for use by other apps to invoke components in your
app), but you usually specify action constants defined by the
Intent class or other framework classes.
– The action in an Intent object can be set by the setAction()
method or with Intent constructor and read by getAction().
Cont . . .
• Intent class defines a number of action constants corresponding
to different intents.
• Here are some common actions for starting an activity:
Sr.No Activity Action Intent & Description
1 ACTION_ALL_APPS - List all the applications available on the device.
2 ACTION_ANSWER - Handle an incoming phone call.
3 ACTION_BATTERY_CHANGED - This is a sticky broadcast containing
the charging state, level, and other information about the battery.
4 ACTION_BATTERY_LOW - This broadcast corresponds to the "Low
battery warning" system dialog.
5 ACTION_BATTERY_OKAY - This will be sent after
ACTION_BATTERY_LOW once the battery has gone back up to an
okay state.
Cont . . .
• See the Intent class reference for more constants that define
generic actions.
Sr.No Activity Action Intent & Description
6 ACTION_CALL - Perform a call to someone specified by the data.
7 ACTION_DATE_CHANGED - The date has changed.
8 ACTION_HEADSET_PLUG - Wired Headset plugged in or unplugged.
10 ACTION_SEARCH - Perform a search.
11 ACTION_SEND - Deliver some data to someone else.
12 ACTION_SENDTO - Send a message to someone specified by the data.
13 ACTION_SEND_MULTIPLE - Deliver multiple data to someone else.
14 ACTION_VIEW - Display the data to the user.
15 ACTION_WEB_SEARCH - Perform a web search.
Cont . . .
• Data
– Adds a data specification to an intent filter.
– The specification can be a data type (the MIME Type attribute),
a URI that references data to be acted on, or both MIME and URI
– When creating an intent, it's often important to specify the type
of data (its MIME type) in addition to its URI.
– For example, an activity that's able to display images probably
won't be able to play an audio file, even though the URI formats
could be similar.
– Specifying the MIME type of your data helps the Android
system find the best component to receive your intent.
– To set only the data URI, call setData() and to set only the
MIME type, call setType(). If necessary, you can set both
explicitly with setDataAndType().
– The URI is read by getData() and the type by getType().
Cont . . .
• Category (optional)
– The category is an optional part of Intent object and it's a
– 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.
– 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 are some common categories:
• CATEGORY_BROWSABLE - 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 - activity is the initial activity of a task
and is listed in the system's application launcher.
• See the Intent class description for the full list of categories.
Cont . . .
• Extras
– A key-value pairs for additional information that should be
delivered to the component handling the intent.
– You can add extra data with various putExtra() methods, each
accepting two parameters: the key name and the value.
– You can also create a Bundle object with all the extra data,
then insert the Bundle in the Intent with putExtras().
– The extras can be read using the getExtras() methods.
– The Intent class specifies many EXTRA_* constants for
standardized data types.
– If you need to declare your own extra keys (for intents that
your app receives), be sure to include your app's package
name as a prefix, as shown in the following example:
– static final String EXTRA_GIGAWATTS = "com.exam.EXTRA_GIGAWATTS“;
Cont . . .
• Flags - An optional part of Intent object that instruct the Android
system how to launch an activity, and how to treat it after it's
launched etc.
Sr.No Flags & Description
1
FLAG_ACTIVITY_CLEAR_TASK
This flag will cause any existing task that would be associated with the activity
to be cleared before the activity is started.
This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.
2
FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current 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.
3
FLAG_ACTIVITY_NEW_TASK
This flag is generally used by activities that want to present a "launcher" 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.
Intent Filter
• 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.
• A component can register itself via an intent filter for a specific
action and specific data.
• An intent filter specifies the types of intents to which an activity,
service, or broadcast receiver can respond to by declaring the
capabilities of a component.
• Android components register intent filters either statically using
<intent-filter> element in the in the AndroidManifest.xml using
or in case of a broadcast receiver also dynamically via code.
• An intent filter is defined by its category, action and data filters.
It can also contain additional meta-data which are list down in
side manifest file.
Cont . . . .
• Example 1: the following part of AndroidManifest.xml file
specify an activity com.exame.Myapplication.CustomActivity
which can be invoked by either of the two mentioned actions,
one category, and one data:
• The above code will register an Activity for the Intent which is
triggered when someone wants to open a webpage.
<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>
Cont . . . .
• Example 2: Register an activity for phone call - The following
code will register an Activity for the Intent which is triggered
when someone wants to make a call.
<?xml version="1.0" encoding="utf-8"?>
<manifest >
. . . . . . . . . . .
<uses-permission android:name="android.permission.CALL_PHONE" />
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Cont . . . .
• Reference
– Android - Intents and Filters
– www.tutorialspoint.com/android/android_intents_filters.html
– www.vogella.com/tutorials/AndroidIntent/article.html
– Android official website (Develop ----- > API Guides/Intents and
Intent Filters and API Guides/Common Intents)
– Phone call
– www.tutorialspoint.com/android/android_phone_calls.html
– Sending SMS
– www.tutorialspoint.com/android/android_sending_sms.html
– Sending eMail
– www.tutorialspoint.com/android/android_sending_email.html
– Alert dialog
– www.tutorialspoint.com/android/android_alert_dialoges.html
Android - Service
Introduction to Service
• A service is a component that runs in the background without
direct interaction with the user.
• It works even if application or component that started the
service is destroyed.
• Services are used for repetitive and potentially long running
operations, i.e., Internet downloads, checking for new data, data
processing, updating content providers etc.
• Services run with a higher priority than inactive or invisible
activities and therefore it is less likely that the Android system
terminates them.
• Services can also be configured to be restarted if they get
terminated by the Android system once sufficient system
resources are available again.
Platform service and custom services
• The Android platform provides and runs predefined system
services and every Android application can use them, given the
right permissions.
• These system services are usually exposed via a specific
Manager class.
• Access to them can be gained via the getSystemService()
method.
• The Context class defines several constants for accessing these
services.
• An Android application can, in addition to consuming the
existing Android platform services, define and use new services.
• Defining your custom services allows you to design responsive
applications.
• You can fetch the application data via it and once the application
is started by the user, it can present fresh data to the user
State of Service
• A service can essentially take three states
1)Started
– A service is started when an application component, such as an activity,
starts it by calling startService().
– Once started, a service can run in the background indefinitely, even if a
component that started it is destroyed.
2)Bound
– 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).
3)Scheduled (exist in Android 5.0 (API 21) and later version)
– A service is scheduled when API such as JobScheduler, launches service.
– You can use the JobScheduler by registering jobs and specifying their
requirements for network and timing.
Foreground services
• A foreground service is a service that should have the same
priority as an active activity
• It should not be killed by the Android system, even if the system
is low on memory.
• A foreground service must provide a notification for the status
bar, which is placed under the "Ongoing" heading, which means
that the notification cannot be dismissed unless the service is
either stopped or removed from the foreground.
Notification notification = new Notification(R.drawable.icon,
getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
Services life cycle
Cont . . .
• A service has life cycle callback methods that you can implement
to monitor changes in the service's state and you can perform
work at the appropriate stage.
• To create an service, you create a Java class that extends the
Service base class or one of its existing subclasses.
• The Service base class defines various callback methods and the
most important are given below
Sr.No. Callback & Description
1
onStartCommand()
The system calls this method when another component,
such as an activity, requests that the service be started,
by calling startService().
If you implement this method, it is your responsibility to
stop the service when its work is done, by calling
stopSelf() or stopService() methods.
Cont . . .
Sr.No. Callback & Description
2 onBind()
The system calls this method when another component wants to
bind with the service by calling bindService().
If you implement this method, you must provide an interface that
clients use to communicate with the service, by returning
an IBinder object.
You must always implement this method, but if you don't want to
allow binding, then you should return null.
3 onUnbind()
The system calls this method when all clients have disconnected
from a particular interface published by the service.
4 onRebind()
The system calls this method when new clients have connected to
the service, after it had previously been notified that all had
disconnected in its onUnbind(Intent).
Cont . . .
Sr.No. Callback & Description
5 onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind().
This call is required to perform one-time set-up.
6 onDestroy()
The system calls this method when the service is no longer
used and is being destroyed.
Your service should implement this to clean up any resources
such as threads, registered listeners, receivers, etc.
Implementation and declaration
• A service needs to be declared in the AndroidManifest.xml file
and the implementing class must extend theService class or one
of its subclasses.
<service
android:name="MyService"
android:icon="@drawable/icon"
android:label="@string/service_name" >
</service>
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
} }
Start a service
• An Android component (service, receiver, activity) can trigger
the execution of a service via the startService(intent) method.
• Alternatively, you can also start a service via
the bindService() method call.
• This allows you to communicate directly with the service.
// use this to start and trigger a service
Intent i= new Intent(context, MyService.class);
// potentially add data to the intent
i.putExtra("KEY1", "Value to be used by the service");
startService(i);
Service start process and execution
• If the startService(intent) method is called and the service is not
yet running, the service object is created and the onCreate()
method of the service is called.
– Once the service is started, the onStartCommand(intent)
method in the service is called. It passes in the Intent object
from the startService(intent) call.
• If startService(intent) is called while the service is running,
its onStartCommand() is also called.
• Therefore your service needs to be prepared that
onStartCommand() can be called several times.
– This method is called by the Android system in the main user
interface thread, and it cannot be called simultaneously from
two different threads.
– A service is only started once, no matter how often you call
the startService() method.
Service restart behavior
• In its onStartCommand() method call, the service returns
an int which defines its restart behavior in case the service gets
terminated by the Android platform.
• You can use the constants, the most common options are
described by the following table.
Option Description
Service.START
_STICKY
Service is restarted if it gets terminated. Intent data passed to
the onStartCommand method is null. Used for services which
manages their own state and do not depend on the Intent data.
Service.START
_NOT_STICKY
Service is not restarted. Used for services which are
periodically triggered anyway. The service is only restarted if
the runtime has pending startService()calls since the service
termination.
Service.START
_REDELIVER_I
NTENT
Similar to Service.START_STICKY but the originalIntent is re-
delivered to the onStartCommandmethod.
Communication with services
• There are several possibilities for a communication between an
activity and a service.
1. Using Intent data
– In a simple scenario no direct communication is required.
– The service receives the intent data from the starting
Android component and performs its work.
– No notification is necessary.
– For example, in case the service updates a content provider,
the activity is notified by the content provider and no extra
step in the service is necessary.
– This approach works for local and services running in their
own process.
Cont . . .
2. Using receiver
– You can use broadcasts and registered receivers for the
communication.
– For example, your activity can register a broadcast receiver
for an event and service sends outs corresponding events.
– This is a very typical scenario, in which the service need to
signal to the activity that his processing has finished.
Exercise:
1. Using services and service communication
2. Define and consume local service
3. Establishing Communication between a Service and an Activity
4. Performing Long-Running Tasks in a Service
5. Performing Repeated Tasks in a Service
6. Executing Asynchronous Tasks on Separate Threads Using
IntentService
7. Binding Activities to Services
• Reference
– www.tutorialspoint.com/android/android_services.html
– www.vogella.com/tutorials/AndroidServices/article.html
– Android official website (Develop ----- > API Guides/Service)
BroadcastReciever
Introduction
• A broadcast receiver (receiver) is an Android component which
allows you to register for system or application events. All
registered receivers for an event are notified by the Android
runtime once this event happens.
• E.g., applications can register for ACTION_BOOT_COMPLETED
system event which is fired once the Android system has
completed the boot process.
• There are two important steps to make BroadcastReceiver
works for the system broadcasted intents
1. Creating the Broadcast Receiver.
2. Registering Broadcast Receiver
• There is one additional steps in case you are going to implement
your custom intents then you will have to create and broadcast
those intents.
Cont . . .
1) Creating the Broadcast Receiver
– A broadcast receiver is implemented as a subclass of
BroadcastReceiver 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();
}
}
Cont . . .
2) Registering Broadcast Receiver
– An application listens for specific broadcast intents by
registering a broadcast receiver in AndroidManifest.xml file.
– Consider we are going to register MyReceiver for system
generated event ACTION_BOOT_COMPLETED which is fired
by the system once the Android system has completed the
boot process.
<receiver
android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
Cont . . .
• Now whenever your Android device gets booted, it will be
intercepted by BroadcastReceiver MyReceiver and implemented
logic inside onReceive() will be executed.
System broadcasts
• Several system events are defined as final static fields in the
Intent class.
• Other Android system classes also define events, e.g., the
TelephonyManager defines events for the change of phone state.
• The following table lists a few important system events.
Event Description
Intent.ACTION_BOOT_COMPLETED
Boot completed. Requires the
android.permission.RECEIVE_BOOT_COM
PLETED permission
Intent.ACTION_POWER_CONNECTED Power got connected to the device.
Intent.ACTION_POWER_DISCONNECTED Power got disconnected to the device.
Intent.ACTION_BATTERY_LOW
Triggered on low battery. Typically used to
reduce activities in your app which
consume power.
Intent.ACTION_BATTERY_OKAY Battery status good again.
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
sendBroadcast() method inside your activity class
• If you use the sendStickyBroadcast(Intent) method, the Intent is
sticky, meaning the Intent you are sending stays around after the
broadcast is complete.
• This intent com.example.CUSTOM_INTENT can also be registered in
similar way as we have regsitered system generated intent.
public void broadcastIntent(View view) {
Intent intent = new Intent();
intent.setAction("com.example.CUSTOM_INTENT");
sendBroadcast(intent);
}
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT"></action>
</intent-filter> </receiver>
Cont . . . .
Exercise:
1. Register a receiver for incoming phone calls
2. Register a receiver for received SMS message
3. System services and receiver
•Reference - BroadcastReciever
– www.tutorialspoint.com/android/android_broadcast_receivers.html
– www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
Thank You
Queries

Intent, Service and BroadcastReciver (2).ppt

  • 1.
    Mobile Application Development (Intent,Service and BroadcastReciver)
  • 2.
    Agenda 1. Intent andfilter – An overview of Intent – Types of Intent – Building Intent object – Intent Filters 2. Android: Service – An overview of Service – State of Service – Life cycle of Service – Implementation of Service 3. BroadcastReciever
  • 3.
  • 4.
    An overview ofIntent • Intents are asynchronous messages which allow application components to request functionality from other Android components. • i.e. An Intent is a messaging object you can use to request an action from another application component. • An Android Intent is an abstract description of an operation to be performed. • Intents allow you to interact with components from the same applications as well as with components contributed by other applications.
  • 5.
    Cont . .. • Intents are objects of the android.content.Intent type. • Your code can send them to the Android system defining the components you are targeting. • Intents facilitate communication between components in several ways, and there are separate mechanisms for delivering intents to each type of component − activities, services, and broadcast receivers. A) Starting an activity – You can start a new instance of an Activity by passing an Intent object to startActivity() method. – The Intent object describes the activity to start and carries any necessary data.
  • 6.
    Cont . .. B) Starting a service – You can start a service to perform a one-time operation (such as downloading a file) by passing an Intent object to startService() method. – With Android 5.0 (API level 21) and later, you can also start a service with JobScheduler. – The Intent object describes the service to start and carries any necessary data. – If the service is designed with a client-server interface, you can bind to the service from another component by passing an Intent object to bindService() method.
  • 7.
    Cont . .. C) Delivering a broadcast – The system delivers various broadcasts for system events, such as when a system boots up or the device starts charging. – You can deliver a broadcast to other applications by passing Intent object to sendBroadcast() or sendOrderedBroadcast() method. • Example: How to use intent object to start Activity and Services as well as to deliver Broadcast Intent myIntent = new Intent(this, TargetActivity.class); startActivity(myIntent); startService(myIntent); sendBroadcast(myIntent);
  • 8.
    Types of Intent •There are following two types of intents supported by Android A) Explicit Intents – It going to be connected internal world of application, – 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. – E.g., you can start a new activity in response to a user action or start a service to download a file in the background.
  • 9.
    Cont . .. B) Implicit Intents – It going to be connected external world of application, – Do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. – E.g., if you want to show the user location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. – The Figure below show how an implicit intent is delivered through the system to start another activity
  • 10.
    Cont . .. Example of explicit and implicit intent – Explicit intent – Implicit intent – the following code tell the Android system to view a webpage Intent i = new Intent(this, ActivityTwo.class); i.putExtra("Value1", "This value one for ActivityTwo "); i.putExtra("Value2", "This value two ActivityTwo"); startActivity(i); Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com")); startActivity(i);
  • 11.
    Building an intentobject • An Intent object carries information that the Android system uses to determine which component to start (such as the exact component name or component category that should receive the intent), plus information that the recipient component uses in order to properly perform the action (such as the action to take and the data to act upon). • The primary information contained in an Intent is the following: – Component name – Action – Data – Category – Extras – Flags
  • 12.
    Cont . .. • Component name – Represents android component such as Activity, Service or BroadcastReceiver class. – If you need to start a specific component in your app, you should specify the component name, to makes an intent explicit, meaning that the intent should be delivered only to appn component defined by the component name. – Without component name, intent is implicit and the system decides which component should receive the intent based on the other intent information (such as action, data, and category which will explained later in this section). – 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. – The component name is set by setComponent(), setClass(), or setClassName() or with the Intent constructor and read by getComponent().
  • 13.
    Cont . .. • Action – It is mandatory element of of the Intent object – A string that specifies a generic action to perform (such as view or pick). – In the case of a broadcast intent, this is the action that took place and is being reported. – The action largely determines how the rest of the intent is structured particularly the information that is contained in the data and extras. – You can specify your own actions for use by intents within your app (or for use by other apps to invoke components in your app), but you usually specify action constants defined by the Intent class or other framework classes. – The action in an Intent object can be set by the setAction() method or with Intent constructor and read by getAction().
  • 14.
    Cont . .. • Intent class defines a number of action constants corresponding to different intents. • Here are some common actions for starting an activity: Sr.No Activity Action Intent & Description 1 ACTION_ALL_APPS - List all the applications available on the device. 2 ACTION_ANSWER - Handle an incoming phone call. 3 ACTION_BATTERY_CHANGED - This is a sticky broadcast containing the charging state, level, and other information about the battery. 4 ACTION_BATTERY_LOW - This broadcast corresponds to the "Low battery warning" system dialog. 5 ACTION_BATTERY_OKAY - This will be sent after ACTION_BATTERY_LOW once the battery has gone back up to an okay state.
  • 15.
    Cont . .. • See the Intent class reference for more constants that define generic actions. Sr.No Activity Action Intent & Description 6 ACTION_CALL - Perform a call to someone specified by the data. 7 ACTION_DATE_CHANGED - The date has changed. 8 ACTION_HEADSET_PLUG - Wired Headset plugged in or unplugged. 10 ACTION_SEARCH - Perform a search. 11 ACTION_SEND - Deliver some data to someone else. 12 ACTION_SENDTO - Send a message to someone specified by the data. 13 ACTION_SEND_MULTIPLE - Deliver multiple data to someone else. 14 ACTION_VIEW - Display the data to the user. 15 ACTION_WEB_SEARCH - Perform a web search.
  • 16.
    Cont . .. • Data – Adds a data specification to an intent filter. – The specification can be a data type (the MIME Type attribute), a URI that references data to be acted on, or both MIME and URI – When creating an intent, it's often important to specify the type of data (its MIME type) in addition to its URI. – For example, an activity that's able to display images probably won't be able to play an audio file, even though the URI formats could be similar. – Specifying the MIME type of your data helps the Android system find the best component to receive your intent. – To set only the data URI, call setData() and to set only the MIME type, call setType(). If necessary, you can set both explicitly with setDataAndType(). – The URI is read by getData() and the type by getType().
  • 17.
    Cont . .. • Category (optional) – The category is an optional part of Intent object and it's a – 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. – 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 are some common categories: • CATEGORY_BROWSABLE - 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 - activity is the initial activity of a task and is listed in the system's application launcher. • See the Intent class description for the full list of categories.
  • 18.
    Cont . .. • Extras – A key-value pairs for additional information that should be delivered to the component handling the intent. – You can add extra data with various putExtra() methods, each accepting two parameters: the key name and the value. – You can also create a Bundle object with all the extra data, then insert the Bundle in the Intent with putExtras(). – The extras can be read using the getExtras() methods. – The Intent class specifies many EXTRA_* constants for standardized data types. – If you need to declare your own extra keys (for intents that your app receives), be sure to include your app's package name as a prefix, as shown in the following example: – static final String EXTRA_GIGAWATTS = "com.exam.EXTRA_GIGAWATTS“;
  • 19.
    Cont . .. • Flags - An optional part of Intent object that instruct the Android system how to launch an activity, and how to treat it after it's launched etc. Sr.No Flags & Description 1 FLAG_ACTIVITY_CLEAR_TASK This flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK. 2 FLAG_ACTIVITY_CLEAR_TOP If set, and the activity being launched is already running in the current 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. 3 FLAG_ACTIVITY_NEW_TASK This flag is generally used by activities that want to present a "launcher" 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.
  • 20.
    Intent Filter • AndroidOS 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. • A component can register itself via an intent filter for a specific action and specific data. • An intent filter specifies the types of intents to which an activity, service, or broadcast receiver can respond to by declaring the capabilities of a component. • Android components register intent filters either statically using <intent-filter> element in the in the AndroidManifest.xml using or in case of a broadcast receiver also dynamically via code. • An intent filter is defined by its category, action and data filters. It can also contain additional meta-data which are list down in side manifest file.
  • 21.
    Cont . .. . • Example 1: the following part of AndroidManifest.xml file specify an activity com.exame.Myapplication.CustomActivity which can be invoked by either of the two mentioned actions, one category, and one data: • The above code will register an Activity for the Intent which is triggered when someone wants to open a webpage. <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>
  • 22.
    Cont . .. . • Example 2: Register an activity for phone call - The following code will register an Activity for the Intent which is triggered when someone wants to make a call. <?xml version="1.0" encoding="utf-8"?> <manifest > . . . . . . . . . . . <uses-permission android:name="android.permission.CALL_PHONE" /> <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
  • 23.
    Cont . .. . • Reference – Android - Intents and Filters – www.tutorialspoint.com/android/android_intents_filters.html – www.vogella.com/tutorials/AndroidIntent/article.html – Android official website (Develop ----- > API Guides/Intents and Intent Filters and API Guides/Common Intents) – Phone call – www.tutorialspoint.com/android/android_phone_calls.html – Sending SMS – www.tutorialspoint.com/android/android_sending_sms.html – Sending eMail – www.tutorialspoint.com/android/android_sending_email.html – Alert dialog – www.tutorialspoint.com/android/android_alert_dialoges.html
  • 24.
  • 25.
    Introduction to Service •A service is a component that runs in the background without direct interaction with the user. • It works even if application or component that started the service is destroyed. • Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers etc. • Services run with a higher priority than inactive or invisible activities and therefore it is less likely that the Android system terminates them. • Services can also be configured to be restarted if they get terminated by the Android system once sufficient system resources are available again.
  • 26.
    Platform service andcustom services • The Android platform provides and runs predefined system services and every Android application can use them, given the right permissions. • These system services are usually exposed via a specific Manager class. • Access to them can be gained via the getSystemService() method. • The Context class defines several constants for accessing these services. • An Android application can, in addition to consuming the existing Android platform services, define and use new services. • Defining your custom services allows you to design responsive applications. • You can fetch the application data via it and once the application is started by the user, it can present fresh data to the user
  • 27.
    State of Service •A service can essentially take three states 1)Started – A service is started when an application component, such as an activity, starts it by calling startService(). – Once started, a service can run in the background indefinitely, even if a component that started it is destroyed. 2)Bound – 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). 3)Scheduled (exist in Android 5.0 (API 21) and later version) – A service is scheduled when API such as JobScheduler, launches service. – You can use the JobScheduler by registering jobs and specifying their requirements for network and timing.
  • 28.
    Foreground services • Aforeground service is a service that should have the same priority as an active activity • It should not be killed by the Android system, even if the system is low on memory. • A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground. Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis()); Intent notificationIntent = new Intent(this, ExampleActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, getText(R.string.notification_title), getText(R.string.notification_message), pendingIntent); startForeground(ONGOING_NOTIFICATION_ID, notification);
  • 29.
  • 30.
    Cont . .. • A service has life cycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. • To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. • The Service base class defines various callback methods and the most important are given below Sr.No. Callback & Description 1 onStartCommand() The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). If you implement this method, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService() methods.
  • 31.
    Cont . .. Sr.No. Callback & Description 2 onBind() The system calls this method when another component wants to bind with the service by calling bindService(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don't want to allow binding, then you should return null. 3 onUnbind() The system calls this method when all clients have disconnected from a particular interface published by the service. 4 onRebind() The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).
  • 32.
    Cont . .. Sr.No. Callback & Description 5 onCreate() The system calls this method when the service is first created using onStartCommand() or onBind(). This call is required to perform one-time set-up. 6 onDestroy() The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.
  • 33.
    Implementation and declaration •A service needs to be declared in the AndroidManifest.xml file and the implementing class must extend theService class or one of its subclasses. <service android:name="MyService" android:icon="@drawable/icon" android:label="@string/service_name" > </service> public class MyService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { //TODO do something useful return Service.START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { //TODO for communication return IBinder implementation return null; } }
  • 34.
    Start a service •An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method. • Alternatively, you can also start a service via the bindService() method call. • This allows you to communicate directly with the service. // use this to start and trigger a service Intent i= new Intent(context, MyService.class); // potentially add data to the intent i.putExtra("KEY1", "Value to be used by the service"); startService(i);
  • 35.
    Service start processand execution • If the startService(intent) method is called and the service is not yet running, the service object is created and the onCreate() method of the service is called. – Once the service is started, the onStartCommand(intent) method in the service is called. It passes in the Intent object from the startService(intent) call. • If startService(intent) is called while the service is running, its onStartCommand() is also called. • Therefore your service needs to be prepared that onStartCommand() can be called several times. – This method is called by the Android system in the main user interface thread, and it cannot be called simultaneously from two different threads. – A service is only started once, no matter how often you call the startService() method.
  • 36.
    Service restart behavior •In its onStartCommand() method call, the service returns an int which defines its restart behavior in case the service gets terminated by the Android platform. • You can use the constants, the most common options are described by the following table. Option Description Service.START _STICKY Service is restarted if it gets terminated. Intent data passed to the onStartCommand method is null. Used for services which manages their own state and do not depend on the Intent data. Service.START _NOT_STICKY Service is not restarted. Used for services which are periodically triggered anyway. The service is only restarted if the runtime has pending startService()calls since the service termination. Service.START _REDELIVER_I NTENT Similar to Service.START_STICKY but the originalIntent is re- delivered to the onStartCommandmethod.
  • 37.
    Communication with services •There are several possibilities for a communication between an activity and a service. 1. Using Intent data – In a simple scenario no direct communication is required. – The service receives the intent data from the starting Android component and performs its work. – No notification is necessary. – For example, in case the service updates a content provider, the activity is notified by the content provider and no extra step in the service is necessary. – This approach works for local and services running in their own process.
  • 38.
    Cont . .. 2. Using receiver – You can use broadcasts and registered receivers for the communication. – For example, your activity can register a broadcast receiver for an event and service sends outs corresponding events. – This is a very typical scenario, in which the service need to signal to the activity that his processing has finished.
  • 39.
    Exercise: 1. Using servicesand service communication 2. Define and consume local service 3. Establishing Communication between a Service and an Activity 4. Performing Long-Running Tasks in a Service 5. Performing Repeated Tasks in a Service 6. Executing Asynchronous Tasks on Separate Threads Using IntentService 7. Binding Activities to Services • Reference – www.tutorialspoint.com/android/android_services.html – www.vogella.com/tutorials/AndroidServices/article.html – Android official website (Develop ----- > API Guides/Service)
  • 40.
  • 41.
    Introduction • A broadcastreceiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens. • E.g., applications can register for ACTION_BOOT_COMPLETED system event which is fired once the Android system has completed the boot process. • There are two important steps to make BroadcastReceiver works for the system broadcasted intents 1. Creating the Broadcast Receiver. 2. Registering Broadcast Receiver • There is one additional steps in case you are going to implement your custom intents then you will have to create and broadcast those intents.
  • 42.
    Cont . .. 1) Creating the Broadcast Receiver – A broadcast receiver is implemented as a subclass of BroadcastReceiver 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(); } }
  • 43.
    Cont . .. 2) Registering Broadcast Receiver – An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file. – Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process. <receiver android:name="MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver>
  • 44.
    Cont . .. • Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed.
  • 45.
    System broadcasts • Severalsystem events are defined as final static fields in the Intent class. • Other Android system classes also define events, e.g., the TelephonyManager defines events for the change of phone state. • The following table lists a few important system events. Event Description Intent.ACTION_BOOT_COMPLETED Boot completed. Requires the android.permission.RECEIVE_BOOT_COM PLETED permission Intent.ACTION_POWER_CONNECTED Power got connected to the device. Intent.ACTION_POWER_DISCONNECTED Power got disconnected to the device. Intent.ACTION_BATTERY_LOW Triggered on low battery. Typically used to reduce activities in your app which consume power. Intent.ACTION_BATTERY_OKAY Battery status good again.
  • 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 sendBroadcast() method inside your activity class • If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete. • This intent com.example.CUSTOM_INTENT can also be registered in similar way as we have regsitered system generated intent. public void broadcastIntent(View view) { Intent intent = new Intent(); intent.setAction("com.example.CUSTOM_INTENT"); sendBroadcast(intent); } <receiver android:name="MyReceiver"> <intent-filter> <action android:name="com.tutorialspoint.CUSTOM_INTENT"></action> </intent-filter> </receiver>
  • 47.
    Cont . .. . Exercise: 1. Register a receiver for incoming phone calls 2. Register a receiver for received SMS message 3. System services and receiver •Reference - BroadcastReciever – www.tutorialspoint.com/android/android_broadcast_receivers.html – www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
  • 48.