0% found this document useful (0 votes)
93 views30 pages

Module 5

Uploaded by

ambily
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views30 pages

Module 5

Uploaded by

ambily
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

EC312 Object Oriented Programming 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

Messaging SMS and MMS

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

Ambily Mohan, Dept of CSE, JBCMET Page 1


EC312 Object Oriented Programming Module 5

Multi-Language Support single direction and bi-directional text.

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

 The software stack is split into Four Layers:


 The application layer
 The application framework
 The libraries and runtime
 The kernel

Ambily Mohan, Dept of CSE, JBCMET Page 2


EC312 Object Oriented Programming Module 5

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.

Ambily Mohan, Dept of CSE, JBCMET Page 3


EC312 Object Oriented Programming Module 5

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.

SETTING UP DEVELOPMENT ENVIRONMENT


You can start your Android application development on either of the following operating
systems:
 Microsoft Windows XP or later version.
 Mac OS X 10.5.8 or later version with Intel chip.
 Linux including GNU C Library 2.7 or later.
Second point is that all the required tools to develop Android applications are freely available
and can be downloaded from the Web. Following is the list of software's you will need before
you start your Android application programming.
 Java JDK5 or JDK6
 Android SDK
 Eclipse IDE for Java Developers (optional)
 Android Development Tools (ADT) Eclipse Plugin (optional)
Here last two components are optional and if you are working on Windows machine then these
components make your life easy while doing Java based application development. So let us have
a look at how to proceed to set the required environment.
Step 1 - Setup Java Development Kit (JDK)
 Download the latest version of Java JDK
 Follow the given instructions to install and configure the setup.
 Set PATH and JAVA_HOME environment variables to refer to the directory that contains
java and javac, typically java_install_dir/bin and java_install_dir respectively.
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15

Step 2 - Setup Android SDK


 Download the latest version of Android SDK.
 Launch Android SDK Manager using the option All Programs -> Android SDK Tools ->
SDK Manager, this will give you following window:

Ambily Mohan, Dept of CSE, JBCMET Page 4


EC312 Object Oriented Programming Module 5

Ambily Mohan, Dept of CSE, JBCMET Page 5


EC312 Object Oriented Programming Module 5

 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.

Step 3 - Setup Eclipse IDE


 Install Eclipse IDE, download the latest Eclipse
 Eclipse can be started by executing the following commands on windows machine, or you can
simply double click on eclipse.exe
%C:\eclipse\eclipse.exe
 After a successful startup, if everything is fine then it should display the following result:

Ambily Mohan, Dept of CSE, JBCMET Page 6


EC312 Object Oriented Programming Module 5

Step 4 - Setup Android Development Tools (ADT) Plugin


 To install Android Development Tool plugin for Eclipse, choose Help -> Software Updates ->
Install New Software. This will display the following dialogue box.

Ambily Mohan, Dept of CSE, JBCMET Page 7


EC312 Object Oriented Programming Module 5

 Click Add button to add ADT Plugin as name and


https://dl-ssl.google.com/android/eclipse as the location. Then click OK to add this location.
Eclipse starts searching for the plug-in available in the given location and finally lists down the
found plugins.

Ambily Mohan, Dept of CSE, JBCMET Page 8


EC312 Object Oriented Programming Module 5

 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.

Ambily Mohan, Dept of CSE, JBCMET Page 9


EC312 Object Oriented Programming Module 5

 If your AVD is created successfully it means your environment is ready for Android application
development.

BASIC BUILDING BLOCKS – ACTIVITIES, SERVICES,


BROADCAST RECEIVERS & CONTENT PROVIDERS
 Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that describes
each component of the application and how they interact.
 There are following four main components that can be used within an Android application:

Components Description

Activities
They dictate the UI and handle the user interaction to the smartphone screen

Services They handle background processing associated with an application.

Ambily Mohan, Dept of CSE, JBCMET Page 10


EC312 Object Oriented Programming Module 5

Broadcast Receivers They handle communication between Android OS and applications.

Content Providers They handle data and database management issues.

Other Application Components

 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.

Ambily Mohan, Dept of CSE, JBCMET Page 11


EC312 Object Oriented Programming Module 5

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.

Ambily Mohan, Dept of CSE, JBCMET Page 12


EC312 Object Oriented Programming Module 5

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.

onStop() This callback is called when the activity is no longer visible.

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

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 offers a client-server interface that allows
components to interact with the service, send requests, get results, and even do
so across processes with inter-process communication (IPC).

Service Lifecycle

Ambily Mohan, Dept of CSE, JBCMET Page 13


EC312 Object Oriented Programming Module 5

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.

Ambily Mohan, Dept of CSE, JBCMET Page 14


EC312 Object Oriented Programming Module 5

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.

Ambily Mohan, Dept of CSE, JBCMET Page 15


EC312 Object Oriented Programming Module 5

 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.

Event Constant Description

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 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.

Ambily Mohan, Dept of CSE, JBCMET Page 16


EC312 Object Oriented Programming Module 5

 A content provider is implemented as a subclass of ContentProvider class and must implement a


standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider
{
}
 Each Android application runs in its own process with its own permissions which keeps an
application data hidden from another application. But sometimes it is required to share data
across applications. This is where content providers become very useful.
 Content providers let you centralize content in one place and have many different applications
access it as needed.
 A content provider behaves very much like a database where you can query it, edit its content, as
well as add or delete content using insert(), update(), delete(), and query() methods. In most
cases this data is stored in an SQlite database.
Steps to create your own content provider.
1. Create a Content Provider class that extends the ContentProvider baseclass.
2. Define your content provider URI address which will be used to access the content.
3. Ccreate your own database to keep the content. Usually, Android uses SQLite database and
framework needs to override onCreate() method which will use SQLite Open Helper method to
create or open the provider's database. When your application is launched, the onCreate() handler
of each of its Content Providers is called on the main application thread.
4. Implement Content Provider queries to perform different database specific operations.
5. Finally register your Content Provider in your activity file using <provider> tag.

List of methods which you need to override in Content Provider class

 onCreate()This method is called when the provider is started.


 query()This method receives a request from a client. The result is returned as a Cursor object.
 insert()This method inserts a new record into the content provider.
 delete()This method deletes an existing record from the content provider.
 update()This method updates an existing record from the content provider.
 getType()This method returns the MIME type of the data at the given URI.

UI COMPONENTS – VIEWS & NOTIFICATIONS


 Your app's user interface is everything that the user can see and interact with.
 Android provides a variety of pre-built UI components such as structured layout objects and UI
controls that allow you to build the graphical user interface for your app.
 Android also provides other UI modules for special interfaces such as dialogs, notifications, and
menus.
 Main components of user interfaces are
1. View classes
2. Notifications

Ambily Mohan, Dept of CSE, JBCMET Page 17


EC312 Object Oriented Programming Module 5

ANDROID VIEW CLASSES

 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.

Different views in android

Ambily Mohan, Dept of CSE, JBCMET Page 18


EC312 Object Oriented Programming Module 5

Most Commonly Used Android View classes:


These views can be used to create a useful input and output fields.
 Text View
 EditText
 Button
 ImageView
 ImageButton
 CheckBox
 Radio button

Text View

 This class is used to display text on the android application screen.


 It also allows user to optionally edit it. Although it contains text editing operations, the basic
class does not allow editing, So Edit Text class is included to do so.
 Syntax For Text View In XML Coding Is:

 XML coding of text view:


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" >

<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>

Ambily Mohan, Dept of CSE, JBCMET Page 19


EC312 Object Oriented Programming Module 5

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:

 XML coding of edit text:


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"android:layout_height="fill_parent"
android:orientation="vertical" >

<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:

Ambily Mohan, Dept of CSE, JBCMET Page 20


EC312 Object Oriented Programming Module 5

 XML coding of Image view:


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" android:gravity="center_horizontal" >

<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:

 XML coding of checkbox:


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"android:layout_height="fill_parent" >

<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

android:text="Formget." android:checked="true" />

<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:

 XML coding of Radio Button:


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"android:layout_height="fill_parent"
android:orientation="vertical" android:gravity="center_horizontal" >

<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>

Ambily Mohan, Dept of CSE, JBCMET Page 22


EC312 Object Oriented Programming Module 5

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:

 XML coding of button:


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" >

<Button
android:id="@+id/button1" android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="Click Here !" />

</LinearLayout>

Image Button View


 Image button is a button but it carries an image on it.
 We can put an image or a certain text on it and when we click it provides the operations assigned
to it.
 Syntax For Image Button In XML Coding Is:

Ambily Mohan, Dept of CSE, JBCMET Page 23


EC312 Object Oriented Programming Module 5

 XML coding of Image button:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"android:layout_height="fill_parent"
android:orientation="vertical" >

<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.

CREATE AND SEND NOTIFICATIONS


 Follow the following steps in your application to create a notification −
Step 1 - Create Notification Builder
 Create a notification builder using NotificationCompat.Builder.build(). You will use
Notification Builder to set various Notification properties like its small and large icons, title,
priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
Step 2 - Setting Notification Properties
 Once you have Builder object, you can set its Notification properties using Builder object as per
your requirement. But this is mandatory to set at least following −
 A small icon, set by setSmallIcon()
 A title, set by setContentTitle()
 Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");

Ambily Mohan, Dept of CSE, JBCMET Page 24


EC312 Object Oriented Programming Module 5

mBuilder.setContentText("Hi, This is Android Notification Detail!");

 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);

// notificationID allows you to update the notification later on.


mNotificationManager.notify(notificationID, mBuilder.build());

Ambily Mohan, Dept of CSE, JBCMET Page 25


EC312 Object Oriented Programming Module 5

COMPONENTS FOR COMMUNICATION–INTENTS & INTENT


FILTERS

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

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);


startActivity(intent);

 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

Intent i = new Intent(Intent.ACTION_VIEW);


i.setData(Uri.parse("http://www.abhiandroid.com"));
startActivity(i);

 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.

Ambily Mohan, Dept of CSE, JBCMET Page 27


EC312 Object Oriented Programming Module 5

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 content://contacts/people/1 -- Display information about the person whose


identifier is "1".
 ACTION_DIAL content://contacts/people/1 -- Display the phone dialer with the person
filled in.

Ambily Mohan, Dept of CSE, JBCMET Page 28


EC312 Object Oriented Programming Module 5

 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”.

Ambily Mohan, Dept of CSE, JBCMET Page 29


EC312 Object Oriented Programming Module 5

 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>

Ambily Mohan, Dept of CSE, JBCMET Page 30

You might also like