ANDROID APPLICATION
PROGRAMMING
Module 1
APPLICATIONS COMPONENTS
1. Activity
2. Services
3. Broadcast Receivers
4. Content Providers
5. Intents
ACTIVITY
• 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, send an email or view a map.
• Each activity is given a window in which to draw its user interface
• An application usually consists of multiple activities that are loosely
bound to each other.
• Each time a new activity starts, the previously activity is stopped,
but the system preserves the activity in a stack
• when a new activity starts, it is pushed onto the back stack and
takes user focus.
Activity Life Cycle
1. onCreate()
This is the first callback and called when the activity is
first created.
2. onStart()
This callback is called when the activity becomes
visible to the user.
3. onResume()
This is called when the user starts interacting with the
application.
4. onPause()
The paused activity does not receive user input and
cannot execute any code and called when the
current activity is being paused and the previous
activity is being resumed.
5. onStop()
This callback is called when the activity is no longer visible.
6. onDestroy()
This callback is called before the activity is destroyed by the
system.
7. onRestart()
This callback is called when the activity restarts after stopping it.
SERVICES
• A service is a component that runs in the
background to perform long-running operations
without needing to interact with the user and it
works even if application is destroyed.
• Services doesn’t have User Interface.
• 3 types of services:
1. Foreground service
2. Background service
3. Bound service
1. FOREGROUND SERVICE
• It performs some operation that is noticeable to the user.
• For example, an audio app would use a foreground service to play an
audio track.
• Foreground services must display a Notification
• Foreground services continue running even when the user isn’t
interacting with the app.
2. BACKGROUND SERVICE
• A background service performs an operation that
isn’t directly noticed by the user.
• For example, if an app used to compact its storage,
that would usually be a background service.
3. BOUND SERVICE
• 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, RECEIVE RESULTS, AND EVEN DO
SO ACROSS PROCESSES WITH INTERPROCESS COMMUNICATION (IPC).
• 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.
A service can essen ally take two states −
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 the
component that started it is destroyed.
Bound
A service is bound when an application component binds to it by calling
bindService().
A bound service is bound to another component such as activity. The activity
can interact with it, send requests, and get result.
A bound service runs as long as components are bound to it. When
components are no longer bound to it, the service is destroyed.
Traditionally, there are two classes you can extend to create a started service:
Service: This is the base class for all services.
When you extend this class, it's important to create a new thread in which the
service can complete all of its work; the service uses your application's main thread
by default, which can slow the performance of any activity that your application is
running.
IntentService: This is a subclass of Service that uses a worker thread to
handle all of the start requests, one at a time.
This is the best option if you don't require that your service handle multiple requests
simultaneously.
Implement onHandleIntent(), which receives the intent for each start
request so that you can complete the background work
Service Life
cycle
BROADCAST RECEIVERS
● Broadcast Receivers respond to broadcast messages from other
applications or from the system itself
● These broadcasts are sent when an event of interest occurs.
● For example, the Android system sends broadcasts when various
system events occur, such as when the system boots up or the
device starts charging.
● Apps can also send custom broadcasts, for example, to notify
other apps of something that they might be interested in (for
example, some new data has been downloaded).
• Apps can register to receive specific broadcasts.
• When a broadcast is sent, the system automatically routes
broadcasts to apps that have subscribed to receive that
particular type of broadcast.
• Generally speaking, broadcasts can be used as a messaging
system across apps and outside of the normal user flow.
About system broadcasts
• The system automatically sends broadcasts when various system
events occur, such as when the system switches in and out of
airplane mode.
• System broadcasts are sent to all apps that are subscribed to
receive the event.
• The broadcast message itself is wrapped in an Intent object whose
action string identifies the event that occurred (for example
android.intent.action.AIRPLANE_MODE).
• The intent may also include additional information bundled into its
extra field. For example, the airplane mode intent includes a
Boolean extra that indicates whether or not Airplane Mode is on.
• For a complete list of system broadcast actions, see the
BROADCAST_ACTIONS.TXT file in the Android SDK.
• Each broadcast action has a constant field associated with it.
• For example, the value of the constant
ACTION_AIRPLANE_MODE_CHANGED is
android.intent.action.AIRPLANE_MODE. Documentation for each
broadcast action is available in its associated constant field.
IMPORTANT SYSTEM EVENTS
● android.intent.action.BATTERY_CHANGED
Sticky broadcast containing the charging state, level, and other information about the
battery.
● android.intent.action.BATTERY_LOW
Indicates low battery condition on the device.
● android.intent.action.BATTERY_OKAY
Indicates the battery is now okay after being low.
● android.intent.action.BOOT_COMPLETED
This is broadcast once, after the system has finished booting.
● android.intent.action.BUG_REPORT
Show activity for reporting a bug.
● android.intent.action.CALL
Perform a call to someone specified by the data.
● android.intent.action.CALL_BUTTON
The user pressed the "call" button to go to the dialer or other
appropriate UI for placing a call.
● android.intent.action.DATE_CHANGED
The date has changed.
● android.intent.action.REBOOT
Have the device reboot.
CONTENT PROVIDER
• Content providers can help an application manage access to
data stored by itself, stored by other apps, and provide a way
to share data with other apps.
• They encapsulate the data, and provide mechanisms for
defining data security.
CONTENT PROVIDER BASICS
• A content provider manages access to a central repository of
data.
• A provider is part of an Android application, which often
provides its own UI for working with the data.
• A content provider presents data to external applications as
one or more tables that are similar to the tables found in a
relational database.
• A row represents an instance of some type of data the
provider collects, and each column in the row represents an
individual piece of data collected for an instance.
• To retrieve data from a provider, follow these basic steps:
1. Request the read access permission for the provider.
2. Define the code that sends a query to the provider.
INTENTS
Android Intent is the message that is passed between components
such as activities, content providers, broadcast receivers, services
etc
It is generally used with startActivity() method to invoke activity,
broadcast receivers etc.
Intent intent = new Intent(CurrentActivity.this,OtherActivity.class);
startActivity(intent);
There are two types of intents in android:
1. Implicit intent
2. Explicit intent
1. IMPLICIT INTENT
Implicit Intent doesn't specify the component.
In such case, intent provides information of available
components provided by the system that is to be invoked.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.cusat.ac.in"));
startActivity(intent);
2. EXPLICIT INTENT
Explicit Intent specifies the component. In such a case, intent
provides the external class to be invoked.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
SOME IMPORTANT METHOD OF INTENT
INTENT FILTERS
Implicit intent uses the intent filter to serve the user request.
The intent filter specifies the types of intents that an activity,
service, or broadcast receiver can respond.
Intent filters are declared in the Android manifest file.
Most of the intent filter are describe by its
1. <action>,
2. <category>
3. <data>
action
Uses the android:name attribute to specify the name of the action being
serviced. Each Intent Filter must have at least one action tag. Actions
should be unique strings that are self-describing. Best practice is to use a
naming system based on the Java package naming conventions.
Examples of common action:
ACTION_VIEW: Use this action in intent with startActivity() when you have
some information that activity can show to the user like showing an image in
a gallery app or an address to view in a map app
ACTION_SEND: You should use this in intent with startActivity() when you
have some data that the user can share through another app, such as an
email app or social sharing app.
category
Uses the android:name attribute to specify under which circumstances
the action should be serviced. Each Intent Filter tag can include multiple
category tags. You can specify your own categories or use the following
standard values provided by Android:
ALTERNATIVE — This category specifies that this action should be available as
an alternative to the default action performed on an item of this data type.
For example, where the default action for a contact is to view it, the
alternative could be to edit it.
SELECTED_ALTERNATIVE — Similar to the ALTERNATIVE category, but
whereas that category will always resolve to a single action using the intent
resolution described next, SELECTED_ALTERNATIVE is used when a list of
possibilities is required.
DEFAULT — Set this to make a component the default action for the data
type specified in the Intent Filter. This is also necessary for Activities that
are launched using an explicit Intent.
HOME — By setting an Intent Filter category as home without specifying
an action, you are presenting it as an alternative to the native home
screen.
LAUNCHER — Using this category makes an Activity appear in the
application launcher.
BROWSABLE — Specifies an action available from within the browser.
When an Intent is fired from within the browser, it will always include the
browsable category. If you want your application to respond to actions
triggered within the browser (e.g., intercepting links to a particular
website), you must include the browsable category.
data
The data tag enables you to specify which data types your component can act
on; you can include several data tags as appropriate. You can use any
combination of the following attributes to specify the data your component
supports:
android:host — Specifies a valid hostname (e.g., google.com).
android:mimetype — Specifies the type of data your component is
capable of handling.
android:path — Specifies valid path values for the URI.
android:port — Specifies valid ports for the specified host.
android:scheme — Requires a particular scheme (e.g.,
content or http)
MANIFEST FILE
Each Android project includes a manifest file, AndroidManifest.xml, stored in
the root of its project hierarchy.
The manifest defines the structure and metadata of your application, its
components, and its requirements.
It includes nodes for each of the Activities, Services, Content Providers, and
Broadcast Receivers that make up your application and, using Intent Filters
and Permissions, determines how they interact with each other and with
other applications.
The manifest can also specify application metadata (such as its icon, version
number, or theme), and additional top-level nodes can specify any required
permissions, unit tests, and define hardware, screen, or platform
requirements (as described next).
The manifest is made up of a root manifest tag with a package
attribute set to the project’s package.
It should also include an xmlns:android attribute that supplies
several system attributes used within the file.
Use the versionCode attribute to define the current application
version as an integer that increases with each version iteration, and
use the versionName attribute to specify a public version that will
be displayed to users.
A manifest file includes the nodes that define the application
components, security settings, test classes, and requirements that
make up the application.
Some of the manifest sub-node tags that are mainly used
are:
Manifest
The main component of the AndroidManifest.xml file is
known as manifest. Additionally, the packaging field
describes the activity class’s package name. It must
contain an <application> element with the xmlns:android
and package attribute specified.
uses-sdk
This node enables you to define a minimum and maximum SDK version that
must be available on a device for your application to function properly, and
target SDK for which it has been designed using a combination of
minSDKVersion, maxSDKVersion, and targetSDKVersion attributes,
respectively.
uses-feature
Android is available on a wide variety of hardware platforms. Use multiple
uses-feature nodes to specify which hardware features your application
requires. This prevents your application from being installed on a device that
does not include a required piece of hardware, such as NFC hardware, as
follows:
<uses-feature android:name=“android.hardware.nfc” />
uses-library
It defines a shared library against which the application must be linked. This
element instructs the system to add the library’s code to the package’s class
loader. It is contained within the <application> element.
uses-permission
As part of the security model, uses-permission tags declare the user
permissions your application requires. Each permission you specify will be
presented to the user before the application is installed. Permissions are
required for many APIs and method calls, generally those with an associated
cost or security implication (such as dialing, receiving SMS, or using the
location-based services).
application
A manifest can contain only one application node. It uses attributes to specify the
metadata for your application (including its title, icon, and theme). During
development you should include a debuggable attribute set to true to enable
debugging, then be sure to disable it for your release builds.
activity
The Activity sub-element of an application refers to an activity that needs to be
specified in the AndroidManifest.xml file. It has various characteristics, like label,
name, theme, launchMode, and others. In the manifest file, all elements must be
represented by <activity>. Any activity that is not declared there won’t run and
won’t be visible to the system. It is contained within the <application> element.
<activity
android:name=".MainActivity"
android:exported="true">
</activity>