Module 5
Module 5
MODULE V
Introduction to Android : Setting up Development Environment, Basic Building blocks – Activities, Services,
Broadcast Receivers & Content providers, UI Components – Views & notifications, Components for
communication Intents & Intent Filters
INTRODUCTION TO ANDROID
Android is an open source and Linux-basedOperating System for mobile devices such as
smartphones and tablet computers.
Android was developed by the Open Handset Alliance, led by Google, and other companies.
It is based on the Linux kernel
Android has its own virtual machine i.e. DVM(Dalvik Virtual Machine),which is used for executing
the android application.
FEATURES OF ANDROID
Feature Description
Beautiful UI Android OS basic screen provides a beautiful and intuitive user interface.
Connectivity GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and
WiMAX.
Storage SQLite, a lightweight relational database, is used for data storage purposes.
Media support H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3,
MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP
Web browser Based on the open-source WebKit layout engine, coupled with Chrome's V8
JavaScript engine supporting HTML5 and CSS3.
Multi-touch Android has native support for multi-touch which was initially made available in
handsets such as the HTC Hero.
Multi-tasking User can jump from one task to another and same time various application can
run simultaneously.
Resizable widgets Widgets are resizable, so users can expand them to show more content or shrink
them to save space
GCM Google Cloud Messaging (GCM) is a service that let developers send short
message data to their users on Android devices, without needing a proprietary
sync solution.
Wi-Fi Direct A technology that let apps discover and pair directly, over a high-bandwidth peer-
to-peer connection.
Android Beam A popular NFC-based technology that let users instantly share, just by touching
two NFC-enabled phones together.
ANDROID ARCHITECTURE
Linux kernel
The architecture is based on the Linux2.6 kernel.
This layer is core of android architecture.
It provides service like power management, memory management, security etc.
It helps in software or hardware binding for better communication.
Native libraries
Android has its own libraries, which is written in c/c+ +.
These libraries cannot be accessed directly.
With the help of application framework, we can access these libraries.
There are many libraries like web Libraries to access web browsers, libraries for android And
video formats etc.
Android run time
T he android runtime was designed specifically for Android to meet the needs of running in
an embedded Environment where you have limited battery, limited Memory, limited cpu.
Dalvik is the process virtual machine in google's Android operating system. It is the software
that runs the Apps on android devices. Dalvik is thus an integral part Of android ,which is
typically used on mobile devices Such as mobile phones and tablet computers.
Programs are commonly written in java and compiled to Byte code.
This is in blue, meaning that it's written in the java programming language.
The core library contains all of the collection Classes, utilities, io, all the utilities and tools
that you’ve come to expected to use.
Application framework
This is all written in a java programming language and The application framework is the
toolkit that all Applications use.
These applications include the ones that come with a Phone like the home applications, or the
phone Application.
It includes applications written by google, and it Includes apps that will be written by you.
So, all apps use the same framework and the same APIS.
These are as follows:-
Activity manager:-it manages the lifecycle of applications. It Enable proper
management of all the activities. All the activities are Controlled by activity manager.
Resource manager:-it provides access to non-code resources such As graphics etc.
Notification manager:-it enables all applications to display Custom alerts in status bar.
Location manager:- it fires alerts when user enters or leaves a specified geographical
location.
Package manager:-it is use to retrieve the data about installed Packages on device.
Window manager:-it is use to create views and layouts.
Telephony manager:-it is use to handle settings of network connection and all
information about services on device.
Application layer
The final layer on top is applications.
It includes the home application the contacts Application , the browser, and apps.
It is the most upper layer in android architecture.
All the applications like camera, google maps, Browser,sms,calendars,contacts are native
Applications. These applications works with end user with the help of application framework
to operate.
Once you launched SDK manager. By default it will list down total 7 packages to be installed,
but we will suggest to de-select Documentation for Android SDK and Samples for SDK
packages to reduce installation time.
Click the Install 7 Packages button to proceed, which will display following dialogue box:
If you agree to install all the packages, select Accept All radio button and proceed by clicking
Install button.
Select all the listed plug-ins using Select All button and click Next button which will guide you
ahead to install Android Development Tools and other required plugins.
Step 5 - Create Android Virtual Device
Launch Android AVD Manager using Eclipse menu options Window -> AVD Manager which
will launch Android AVD Manager.
Use New button to create a new Android Virtual Device and enter the following information,
before clicking Create AVD button.
If your AVD is created successfully it means your environment is ready for Android application
development.
Components Description
Activities
They dictate the UI and handle the user interaction to the smartphone screen
There are a few other application components that you should be aware of.
These application components include fragments, views, layouts, intents, resources, and
manifest.
All of these components are used for the creation of above components.
Application
Description
Components
Fragments * Represents the fragments of a user interface in the Activity component
Views * Includes the user interface elements like buttons, drop-down lists, etc.
* Controls the screen format based on different hierarchies of the views
Layouts
* Takes care of the appearance of the views on the screen
Intents * Wires the messages of different components together
* Includes external elements like drawable or editable pictures, strings, and
Resources
constants
* Carries the information regarding the applications
Manifest
* Configuration file
ACTIVITIES
An activity represents a single screen with a user interface.
An activity is a single screen in an application with UI components, user is going to interact with
the device through the activity.
For example, an email application might have one activity that shows a list of new emails,
another activity to compose an email, and one for reading emails. If an application has more than
one activity, then one of them should be marked as the activity that is presented when the
application is launched.
An activity is implemented as a subclass of Activity class as follows:
public class MainActivity extends Activity
{
}
Activity-lifecycle
To navigate transitions between stages of the activity lifecycle, the Activity class provides a core
set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy().
The system invokes each of these callbacks as an activity enters a new state.
Callback Description
onCreate()
This is the first callback and called when the activity is first created.
onStart() This callback is called when the activity becomes visible to the user
onResume() This is called when the user starts interacting with the application.
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.
onDestroy() This callback is called before the activity is destroyed by the system.
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
any user interaction.
For example, a service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user interaction with an
activity.
A service is implemented as a subclass of Service class as follows:
public class MyService extends Service
{
}
Two states of a services
State Description
Service Lifecycle
Callback Description
onStartCommand() The system calls this method when another component, such as an
activity, requests that the service be started, by callingstartService(). If
you implement this method, it is your responsibility to stop the service
when its work is done, by callingstopSelf()orstopService() methods.
onBind() The system calls this method when another component wants to bind with
the service by callingbindService(). If you implement this method, you
must provide an interface that clients use to communicate with the
service, by returning anIBinderobject. You must always implement this
method, but if you don't want to allow binding, then you should
returnnull.
onUnbind() The system calls this method when all clients have disconnected from a
particular interface published by the service.
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
itsonUnbind(Intent).
onCreate() The system calls this method when the service is first created using
onStartCommand()oronBind(). This call is required to perform one-time
setup.
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.
BROADCAST RECEIVERS
Broadcast Receivers simply respond to broadcast messages from other applications or from the
system.
For example, applications can also initiate broadcasts to let other applications know that some
data has been downloaded to the device and is available for them to use, so this is broadcast
receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message
is broadcasted as an Intent object.
public class MyReceiver extends BroadcastReceiver
{
}
There are following two important steps to make BroadcastReceiver work for the system
broadcasted intents:
1. Creating the Broadcast Receiver.
2. Registering Broadcast Receiver
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 anIntentobject parameter.
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
Registering Broadcast Receiver
An application listens for specific broadcast intents by registering a broadcast receiver in
AndroidManifest.xml file.
Eg: 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.
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
There are several system generated events defined as final static fields in the Intent class. The
following table lists a few important system events.
CONTENT PROVIDERS
A content provider component supplies data from one application to other on request. Such
requests are handled by the methods of the ContentResolver class.
A content provider can use different ways to store its data and the data can be stored in a
database, in files, or even over a network.
View Class are the basic building block for user interface components.
A View occupies a 2-dimensional area (say: rectangle) on the screen, which is responsible for
framing and handling different type of events.
Views are used to create input and output fields in the an Android App. It can be input text field,
radio field, image field etc. They are same as, input text field, image tag to show images, radio
field in HTML.
Text View
<TextView
android:id="@+id/myTextview" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Mangnet Brains"
android:textSize="25dp" android:textColor="@android:color/black"
android:typeface="serif" android:gravity="center" android:padding="10dp"
android:layout_margin="20dp" />
</LinearLayout>
Edit Text
This class makes text to be editable in Android application. It helps in building the data interface
taken from any user, also contains certain features through which we can hide the data which
are confidential.
Syntax For Edit Text In XML Coding Is:
<EditText
android:id="@+id/myEdittext" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textSize="20dp"
android:textStyle="bold" android:typeface="serif" android:gravity="center"
android:padding="10dp" android:layout_margin="20dp"
android:hint="Enter a Number" android:singleLine="true"
android:inputType="textPassword" />
</LinearLayout>
Image view
Image view helps to display images in an android application.
Any image can be selected, we just have to paste our image in a drawable folder from where we
can access it. For example: In below Code “@drawable/ic_laucher” has been taken.
Syntax For Image View In XML Coding Is:
<ImageView
android:id="@+id/myimageview" android:layout_width="100dp"
android:layout_height="100dp" android:layout_margin="20dp"
android:gravity="center" android:padding="10dp"
android:src="@drawable/ic_launcher" />
</LinearLayout >
Check Box
Checkbox is used in that applications where we have to select one option from multiple provided.
Checkbox is mainly used when 2 or more options are present.
Syntax For CheckBox In XML Coding Is:
<CheckBox
android:id="@+id/checkBox1" android:layout_width="100dp"
android:layout_height="wrap_content" android:layout_margin="20dp"
Ambily Mohan, Dept of CSE, JBCMET Page 21
EC312 Object Oriented Programming Module 5
<CheckBox
android:id="@+id/checkBox2" android:layout_width="100dp"
android:layout_height="wrap_content" android:layout_margin="20dp"
android:text="Mailget." />
</LinearLayout>
Radio Button
Radio button is like checkbox, but there is slight difference between them.
Radio button is a two-states button that can be either checked or unchecked.
Syntax For Radio Button In XML Coding Is:
<RadioButton
android:id="@+id/radioButton1" android:layout_width="100dp"
android:layout_height="wrap_content" android:layout_margin="20dp"
android:text="Formget" android:checked="true" />
<RadioButton
android:id="@+id/radioButton1" android:layout_width="100dp"
android:layout_height="wrap_content" android:layout_margin="20dp"
android:text="Mailget" />
</LinearLayout>
Button View
This class is used to create a button on an application screen.
Buttons are very helpful in getting into a content.
Android button represents a clickable push-button widget.
Syntax For Button In XML Coding Is:
<Button
android:id="@+id/button1" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Click Here !" />
</LinearLayout>
<ImageButton
android:id="@+id/imageButton1" android:layout_width="match_parent"
android:layout_height="wrap_content"android:layout_gravity="center"
android:src="@drawable/ic_launcher" />
</LinearLayout>
NOTIFICATIONS
A notification is a message you can display to the user outside of your application's normal UI.
When you tell the system to issue a notification, it first appears as an icon in the notification area.
To see the details of the notification, the user opens the notification drawer. Both the notification
area and the notification drawer are system-controlled areas that the user can view at any time.
Android Toast class provides a handy way to show users alerts but problem is that these alerts are
not persistent which means alert flashes on the screen for a few seconds and then disappears.
Three types of android notifications
Toast Notification – Shows message that fades away after a few seconds. (Background type
also)
Status Notification – Shows notification message and displayed till user action. (Background
type also)
Dialog Notification – Comes out of an active Activity.
You have plenty of optional properties which you can set for your notification. To learn more
about them, see the reference documentation for NotificationCompat.Builder.
Step 3 - Attach Actions
This is an optional part and required if you want to attach an action with the notification. An
action allows users to go directly from the notification to an Activity in your application, where
they can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your
application. To associate the PendingIntent with a gesture, call the appropriate method of
NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the
notification text in the notification drawer, you add the PendingIntent by calling
setContentIntent().
A PendingIntent object helps you to perform an action on your applications behalf, often at a later
time, without caring of whether or not your application is running.
We take help of stack builder object which will contain an artificial back stack for the started
Activity. This ensures that navigating backward from the Activity leads out of your application to
the Home screen.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Step 4 - Issue the notification
Finally, you pass the Notification object to the system by calling NotificationManager.notify()
to send your notification. Make sure you call NotificationCompat.Builder.build() method on
builder object before notifying it. This method combines all of the options that have been set and
return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
INTENTS
Android uses Intent for communicating between the components of an Application and also
from one application to another application.
Intent are the objects which is used in android for passing the information among Activities in an
Application and from one app to another also.
Intent are used for communicating between the Application components and it also provides the
connectivity between two apps.
Intent is a messaging object you can use to request an action from another app component. Even
though intents facilitate communication between components in many ways, there are three basic
use-cases:
To initiate an activity
An Activity stands for a unitary screen in an app.
You can begin a new instance of an Activity by passing Intent to startActivity().
The Intent describes the movement to start and carries any necessary data. If you want to receive
a result from the activity when it finishes, call startActivityForResult (). Your activity receives
the result as a break up Intent object in your activity’s onActivityResult() callback.
To start a service
A Service is a component that performs operations in the background without a user interface.
You can start a service to perform a one-time operation (such as download a file) by passing
an Intent to startService(). The Intent describes the service to start and carries any necessary data.
If the service is designed with a client-server interface, you can unite to the service from another
section by passing an Intent to bindService().
To deliver a broadcast
A broadcast is a message that can be received by any app.
The system delivers different broadcasts for system events, like when the system boots up or the
device begins charging. You can deliver a broadcast to other apps by passing
an Intent to sendBroadcast (), sendOrderedBroadcast(), or sendStickyBroadcast().
TYPES OF INTENTS
1. Explicit Intent
2. Implicit Intent
Explicit Intent
Explicit Intents are used to connect the application internally.
In Explicit we use the name of component which will be affected by Intent. For Example: If we
know class name then we can navigate the app from One Activity to another activity using Intent.
In the similar way we can start a service to download a file in background process.
Explicit Intent work internally within an application to perform navigation and data transfer.
Ambily Mohan, Dept of CSE, JBCMET Page 26
EC312 Object Oriented Programming Module 5
The below given code snippet will help you understand the concept of Explicit Intents
Here SecondActivity is the JAVA class name where the activity will now be navigated.
Implicit Intent:
In Implicit Intents we do need to specify the name of the component.
We just specify the Action which has to be performed and further this action is handled by the
component of another application.
The basic example of implicit Intent is to open any web page
Let’s take an example to understand Implicit Intents more clearly. We have to open a website
using intent in your application. See the code snippet given below
Unlike Explicit Intent you do not use any class name to pass through Intent(). In this example we
has just specified an action. Now when we will run this code then Android will automatically
start your web browser and it will open AbhiAndroid home page.
BUILDING AN INTENT
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
The name of the component to start.
This is optional, but it's the critical piece of information that makes an intent explicit, meaning
that the intent should be delivered only to the app component defined by the component name.
Without a component name, the intent is implicit and the system decides which component
should receive the intent based on the other intent information (such as the action, data, and
category—described below). If you need to start a specific component in your app, you should
specify the component name.
Action
A string that specifies the generic action to perform (such as view or pick).
Data
The data to operate on, such as a person record in the contacts database, expressed as a Uri.
The URI (a Uri object) that references the data to be acted on and/or the MIME type of that data.
The type of data supplied is generally dictated by the intent's action.
Some examples of action/data pairs are:
ACTION_VIEW tel:123 -- Display the phone dialer with the given number filled in. Note
how the VIEW action does what is considered the most reasonable thing for a particular URI.
ACTION_DIAL tel:123 -- Display the phone dialer with the given number filled in.
ACTION_EDIT content://contacts/people/1 -- Edit information about the person whose
identifier is "1".
ACTION_VIEW content://contacts/people/ -- Display a list of people, which the user can
browse through. This example is a typical top-level entry into the Contacts application,
showing you the list of people. Selecting a particular person to view would result in a new
intent { ACTION_VIEW content://contacts/people/N } being used to start an activity to
display that person.
Category
Gives additional information about the action to execute.
For example, CATEGORY_LAUNCHER means it should appear in the Launcher as a top-level
application, while CATEGORY_ALTERNATIVE means it should be included in a list of
alternative actions the user can perform on a piece of data.
Type
Specifies an explicit type (a MIME type) of the intent data. Normally the type is inferred from
the data itself. By setting this attribute, you disable that evaluation and force an explicit type.
Component
Specifies an explicit name of a component class to use for the intent. Normally this is determined
by looking at the other information in the intent (the action, data/type, and categories) and
matching that with a component that can handle it. If this attribute is set then none of the
evaluation is performed, and this component is used exactly as is. By specifying this attribute, all
of the other Intent attributes become optional.
Extras
This is a Bundle of any additional information. This can be used to provide extended information
to the component. For example, if we have a action to send an e-mail message, we could also
include extra pieces of data here to supply a subject, body, etc.
INTENT FILTERS
In android, Intent Filter is an expression in app’s manifest file (ActivityMainfest.xml) and it is
used to specify the type of intents that the component would like to receive.
In case if we create Intent Filter for an activity, there is a possibility for other apps to start our
activity by sending a certain type of intent otherwise the activity can be started only by an
explicit intent.
Attributes of <intent-filter>
android:icon : An icon represents the activity, service or broadcast receiver when a user interact
with it or when it appears to user in an application. To set an icon you need to give reference of
drawable resource as declared android:icon=”@drawable/icon”.
android:label : A label represents the title of an activity on the toolbar. You can have different
Labels for different Activities as per your requirement or choice. The label should be set as a
reference to a string resource.
android:priority : It provides information about how able an activity is to respond to an intent
that matches the filter, relative to other activities that could also respond to the intent. When an
intent could be handled by multiple activities with different priorities, Android will consider only
those with higher priority values as potential targets for the intent. It controls the order in which
broadcast receivers are executed to receive broadcast messages. Those with higher priority values
are called before those with lower values. (The order applies only to synchronous messages; it's
ignored for asynchronous messages.). Use this attribute only if you really need to impose a
specific order in which the broadcasts are received, or want to force Android to prefer one
activity over others. The value must be an integer, such as "100". Higher numbers have a higher
priority. The default value is 0.
<intent-filter android:icon="drawable resource" android:label="string resource"
android:priority="integer" >
........
........
</intent-filter>
Nested Elements of <intent-filter>
Intent Filters (<intent-filter>) whatever we define in manifest file can be nested in the
corresponding app components and we can specify the type of intents to accept using these three
elements.
<action> : It defines the name of an intent action to be accepted and it must be a literal string
value of an action, not the class constant.
<category> : It defines the name of an intent category to be accepted and it must be the literal
string value of an action, not the class constant.
<data> : It defines the type of data to be accepted and by using one or more attributes we can
specify various aspects of the data URI (scheme, host, port, path) and MIME type.
Following is the code snippet of defining an activity with Intent Filter (<intent-filter>) in
Android Manifest file (AndroidManifest.xml) like as shown below.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>