0% found this document useful (0 votes)
24 views

MC4204 - Mobile Application Development

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

MC4204 - Mobile Application Development

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

Scanned by TapScanner

Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Generic User Interface


The Generic User Interface (Generic UI, GUI) framework allows you to create UI screens using
Java and XML. XML is optional but it provides a declarative approach to the screen layout and
reduces the amount of code which is required for building the user interface.

Figure 10. The Structure of Generic User Interface


The application screens consist of the following parts:
 Descriptors – XML files for declarative definition of the screen layout and data components.
 Controllers – Java classes for handling events generated by the screen and its UI controls and
for programmatic manipulation with the screen components.
The code of application screens interacts with visual component interfaces (VCL Interfaces).
These interfaces are implemented using the Vaadin framework components.
Visual Components Library (VCL) contains a large set of ready-to-use components.
Data components provide a unified interface for binding visual components to entities and for
working with entities in screen controllers.
Infrastructure includes the main application window and other common client mechanisms.
1.1 Android - UI Layouts
The basic building block for user interface is a View object which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling.
View is the base class for widgets, which are used to create interactive UI components like
buttons, text fields, etc.

pg. 1
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/ViewGroup objects or you can declare your layout using simple XML
file main_layout.xml which is located in the res/layout folder of your project.

Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout
may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a
simple example of XML file having LinearLayout −
<?xml version="1.0" encoding="utf-8"?>
<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/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />

pg. 2
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

<!-- More GUI components go here -->

</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Android Layout Types


There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.

Sr.No Layout & Description

1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction,
vertically or horizontally.

2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.

3 Table Layout
TableLayout is a view that groups views into rows and columns.

4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.

5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a
single view.

6 List View
ListView is a view group that displays a list of scrollable items.

pg. 3
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable
grid.

Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and their are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:

Sr.No Attribute & Description

1
android:id
This is the ID which uniquely identifies the view.

2
android:layout_width
This is the width of the layout.

3
android:layout_height
This is the height of the layout

4
android:layout_marginTop
This is the extra space on the top side of the layout.

5
android:layout_marginBottom
This is the extra space on the bottom side of the layout.

6
android:layout_marginLeft
This is the extra space on the left side of the layout.

7
android:layout_marginRight
This is the extra space on the right side of the layout.

8
android:layout_gravity

pg. 4
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

This specifies how child Views are positioned.

9
android:layout_weight
This specifies how much of the extra space in the layout should be allocated to
the View.

10
android:layout_x
This specifies the x-coordinate of the layout.

11
android:layout_y
This specifies the y-coordinate of the layout.

12
android:layout_width
This is the width of the layout.

13
android:paddingLeft
This is the left padding filled for the layout.

14
android:paddingRight
This is the right padding filled for the layout.

15
android:paddingTop
This is the top padding filled for the layout.

16
android:paddingBottom
This is the bottom padding filled for the layout.

Here width and height are the dimension of the layout/view which can be specified in terms of
dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an
inch), px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one of
these constants to set the width or height −
 android:layout_width=wrap_content tells your view to size itself to the dimensions
required by its content.

pg. 5
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

 android:layout_width=fill_parent tells your view to become as big as its parent view.


Gravity attribute plays important role in positioning the view object and it can take one or more
(separated by '|') of the following constant values.

Constant Value Description

top 0x30 Push object to the top of its container, not changing
its size.

bottom 0x50 Push object to the bottom of its container, not


changing its size.

left 0x03 Push object to the left of its container, not changing
its size.

right 0x05 Push object to the right of its container, not changing
its size.

center_vertical 0x10 Place object in the vertical center of its container, not
changing its size.

fill_vertical 0x70 Grow the vertical size of the object if needed so it


completely fills its container.

center_horizontal 0x01 Place object in the horizontal center of its container,


not changing its size.

fill_horizontal 0x07 Grow the horizontal size of the object if needed so it


completely fills its container.

center 0x11 Place the object in the center of its container in both
the vertical and horizontal axis, not changing its size.

fill 0x77 Grow the horizontal and vertical size of the object if
needed so it completely fills its container.

clip_vertical 0x80 Additional option that can be set to have the top
and/or bottom edges of the child clipped to its
container's bounds. The clip will be based on the

pg. 6
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

vertical gravity: a top gravity will clip the bottom


edge, a bottom gravity will clip the top edge, and
neither will clip both edges.

clip_horizontal 0x08 Additional option that can be set to have the left
and/or right edges of the child clipped to its
container's bounds. The clip will be based on the
horizontal gravity: a left gravity will clip the right
edge, a right gravity will clip the left edge, and
neither will clip both edges.

start 0x00800003 Push object to the beginning of its container, not


changing its size.

end 0x00800005 Push object to the end of its container, not changing
its size.

View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within
the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
Following is a brief description of @ and + signs −
 The at-symbol (@) at the beginning of the string indicates that the XML parser should
parse and expand the rest of the ID string and identify it as an ID resource.
 The plus-symbol (+) means that this is a new resource name that must be created and
added to our resources. To create an instance of the view object and capture it from the
layout, use the following −
Button myButton = (Button) findViewById(R.id.my_button);

1.2 Android - UI Controls


Input controls are the interactive components in your app's user interface. Android provides a
wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check
box, zoom buttons, toggle buttons, and many more.

pg. 7
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

UI Elements
A View is an object that draws something on the screen that the user can interact with and
a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the
layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML. For example, a simple vertical layout with a text view and a button looks like
this −
<?xml version="1.0" encoding="utf-8"?>
<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/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>

Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user
interface for your app.

pg. 8
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Sr.No. UI Control & Description

1 TextView
This control is used to display text to the user.

2 EditText
EditText is a predefined subclass of TextView that includes rich editing
capabilities.

3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it
shows a list of completion suggestions automatically while the user is typing.

4 Button
A push-button that can be pressed, or clicked, by the user to perform an action.

5 ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact
location of its children. This shows a button with an image (instead of text)
that can be pressed or clicked by the user.

6 CheckBox
An on/off switch that can be toggled by the user. You should use check box
when presenting users with a group of selectable options that are not mutually
exclusive.

7 ToggleButton
An on/off button with a light indicator.

8 RadioButton
The RadioButton has two states: either checked or unchecked.

9 RadioGroup
A RadioGroup is used to group together one or more RadioButtons.

pg. 9
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks,
such as when you are performing a task in the background.

11 Spinner
A drop-down list that allows users to select one value from a set.

12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-
hour mode or AM/PM mode.

13 DatePicker
The DatePicker view enables users to select a date of the day.

Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides a
wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check
box, zoom buttons, toggle buttons, and many more.
As explained in previous chapter, a view object may have a unique ID assigned to it which will
identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file and
assign it a unique ID as follows −
<?xml version="1.0" encoding="utf-8"?>
<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/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the
following −
TextView myText = (TextView) findViewById(R.id.text_id);

pg. 10
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

1.3 Android - Event Handling


Events are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc. The Android framework
maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in your
program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −
 Event Listeners − An event listener is an interface in the View class that contains a single
callback method. These methods will be called by the Android framework when the View
to which the listener has been registered is triggered by user interaction with the item in
the UI.
 Event Listeners Registration − Event Registration is the process by which an Event
Handler gets registered with an Event Listener so that the handler is called when the Event
Listener fires the event.
 Event Handlers − When an event happens and we have registered an event listener for the
event, the event listener calls the Event Handlers, which is the method that actually
handles the event.
Event Listeners & Event Handlers

Event Handler Event Listener & Description

OnClickListener()
onClick() This is called when the user either clicks or touches or
focuses upon any widget like button, text, image etc. You
will use onClick() event handler to handle such event.

OnLongClickListener()

onLongClick() This is called when the user either clicks or touches or


focuses upon any widget like button, text, image etc. for one
or more seconds. You will use onLongClick() event handler
to handle such event.

OnFocusChangeListener()
onFocusChange() This is called when the widget looses its focus ie. user goes
away from the view item. You will use onFocusChange()
event handler to handle such event.

pg. 11
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

OnFocusChangeListener()
onKey() This is called when the user is focused on the item and
presses or releases a hardware key on the device. You will
use onKey() event handler to handle such event.

OnTouchListener()
onTouch() This is called when the user presses the key, releases the key,
or any movement gesture on the screen. You will use
onTouch() event handler to handle such event.

OnMenuItemClickListener()
onMenuItemClick()
This is called when the user selects a menu item. You will
use onMenuItemClick() event handler to handle such event.

onCreateContextMenuItemListener()
onCreateContextMenu()
This is called when the context menu is being built(as the
result of a sustained "long click)

There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So I recommend to refer official
documentation for Android application development in case you are going to develop a
sophisticated apps.
Event Listeners Registration
Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are
several tricky ways to register your event listener for any event, but I'm going to list down only
top 3 ways, out of which you can use any of them based on the situation.
 Using an Anonymous Inner Class
 Activity class implements the Listener interface.
 Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios −
Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by
touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode
by calling the View class‟s isInTouchMode() method.

pg. 12
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Focus
A view or widget is usually highlighted or displays a flashing cursor when it‟s in focus. This
indicates that it‟s ready to accept input from the user.
 isFocusable() − it returns true or false
 isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A
view may be focusable when using a hardware key but not when the device is in touch
mode)
android:foucsUp="@=id/button_l"

onTouchEvent()
public boolean onTouchEvent(motionEvent event){
switch(event.getAction()){
case TOUCH_DOWN:
Toast.makeText(this,"you have clicked down Touch button",Toast.LENTH_LONG).show();
break();

case TOUCH_UP:
Toast.makeText(this,"you have clicked up touch button",Toast.LENTH_LONG).show();
break;

case TOUCH_MOVE:
Toast.makeText(this,"you have clicked move touch button"Toast.LENTH_LONG).show();
break;
}
return super.onTouchEvent(event) ;
}

Event Handling Examples


Event Listeners Registration Using an Anonymous Inner Class
Here you will create an anonymous implementation of the listener and will be useful if each class
is applied to a single control only and you have advantage to pass arguments to event handler. In
this approach event handler methods can access private data of Activity. No reference is needed
to call to Activity.
But if you applied the handler to more than one control, you would have to cut and paste the
code for the handler and if the code for the handler is long, it makes the code harder to maintain.
Following are the simple steps to show how we will make use of separate Listener class to
register and capture click event. Similar way you can implement your listener for any other
required event type.

pg. 13
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Step Description

1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.

2 Modify src/MainActivity.java file to add click event listeners and handlers for
the two buttons defined.

3 Modify the detault content of res/layout/activity_main.xml file to include


Android UI controls.

4 No need to declare default string constants.Android studio takes care default


constants.

5 Run the application to launch Android emulator and verify the result of the
changes done in the aplication.

Following is the content of the modified main activity


file src/com.example.myapplication/MainActivity.java. This file can include each of the
fundamental lifecycle methods.
package com.example.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {


private ProgressDialog progress;
Button b1,b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);

b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);

pg. 14
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(25);
}
});

b2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(55);
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>

<TextView
android:id="@+id/textView2"

pg. 15
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small font"
android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Font"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25dp" />

</RelativeLayout>

pg. 16
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Following will be the content of res/values/strings.xml to define two new constants −


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>

Following is the default content of AndroidManifest.xml −


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.myapplication.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>
Let's try to run your myapplication application. I assume you had created your AVD while
doing environment setup. To run the app from Android Studio, open one of your project's
activity files and click Run icon from the toolbar. Android Studio installs the app on your
AVD and starts it and if everything is fine with your setup and application, it will display
following Emulator window −

pg. 17
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Now you try to click on two buttons, one by one and you will see that font of the Hello
World text will change, which happens because registered click event handler method is being
called against each click event.
Exercise
I will recommend to try writing different event handlers for different event types and understand
exact difference in different event types and their handling. Events related to menu, spinner,
pickers widgets are little different but they are also based on the same concepts as explained
above.
1.4 Android - Styles and Themes
A style resource defines the format and look for a UI. A style can be applied to an individual
View (from within a layout file) or to an entire Activity or application (from within the manifest
file).
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout.
This XML file resides under res/values/ directory of your project and will have <resources> as
the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it
must use the .xml extension.
You can define multiple styles per file using <style> tag but each style will have its name that
uniquely identifies the style. Android style attributes are set using <item> tag as shown below −
<?xml version="1.0" encoding="utf-8"?>
<resources>

pg. 18
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
The value for the <item> can be a keyword string, a hex color, a reference to another resource
type, or other value depending on the style property.
Using Styles
Once your style is defined, you can use it in your XML Layout file using style attribute as
follows −
<?xml version="1.0" encoding="utf-8"?>
<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/text_id"
style="@style/CustomFontStyle"
android:text="@string/hello_world" />

</LinearLayout>
To understand the concept related to Android Style, you can check Style Demo Example.
Style Inheritance
Android supports style Inheritance in very much similar way as cascading style sheet in web
design. You can use this to inherit properties from an existing style and then define only the
properties that you want to change or add.
To implement a custom theme create or edit MyAndroidApp/res/values/themes.xml and add the
following −
<resources>
...
<style name="MyCustomTheme" parent="android:style/Theme">
<item name="android:textColorPrimary">#ffff0000</item>
</style>
...
</resources>

pg. 19
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

In your AndroidManifest.xml apply the theme to the activities you want to style −
<activity
android:name="com.myapp.MyActivity"
...
android:theme="@style/MyCustomTheme"
/>
Your new theme will be applied to your activity, and text is now bright red.

Applying Colors to Theme Attributes


Your color resource can then be applied to some theme attributes, such as the window
background and the primary text color, by adding <item> elements to your custom theme. These
attributes are defined in your styles.xml file. For example, to apply the custom color to the
window background, add the following two <item> elements to your custom theme, defined in
MyAndroidApp/res/values/styles.xml file −
<resources>
...
<style name="MyCustomTheme" ...>
<item name="android:windowBackground">@color/my_custom_color</item>
<item name="android:colorBackgroundCacheHint">@color/my_custom_color</item>
</style>
...
</resources>

pg. 20
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Using a Custom Nine-Patch With Buttons


A nine-patch drawable is a special kind of image which can be scaled in width and height while
maintaining its visual integrity. Nine-patches are the most common way to specify the
appearance of Android buttons, though any drawable type can be used.

a Sample of Nine-Patch button


Steps to create Nine-Patch Buttons
 Save this bitmap as /res/drawable/my_nine_patch.9.png
 Define a new style
 Apply the new button style to the buttonStyle attribute of your custom theme

Define a new Style


<resources>
...
<style name="MyCustomButton" parent="android:Widget.Button">
<item name="android:background">@drawable/my_nine_patch</item>
</style>
...
</resources>
Apply the theme
<resources>
...
<style name="MyCustomTheme" parent=...>
...

pg. 21
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

<item name="android:buttonStyle">@style/MyCustomButton</item>
</style>
...
</resources>

Android Themes
Hope you understood the concept of Style, so now let's try to understand what is a Theme. A
theme is nothing but an Android style applied to an entire Activity or application, rather than an
individual View.
Thus, when a style is applied as a theme, every View in the Activity or application will apply
each style property that it supports. For example, you can apply the
same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will
have green monospace font.
To set a theme for all the activities of your application, open the AndroidManifest.xml file and
edit the <application> tag to include the android:theme attribute with the style name. For
example −
<application android:theme="@style/CustomFontStyle">
But if you want a theme applied to just one Activity in your application, then add the
android:theme attribute to the <activity> tag only. For example −
<activity android:theme="@style/CustomFontStyle">
There are number of default themes defined by Android which you can use directly or inherit
them using parent attribute as follows –

pg. 22
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

<style name="CustomTheme" parent="android:Theme.Light">


...
</style>
To understand the concept related to Android Theme, you can check Theme Demo Example.
Styling the colour palette
The layout design can implementable based on them based colours, for example as following
design is designed based on them colour(blue)

Above layout has designed based on style.xml file,Which has placed at res/values/
<resource>
<style name="AppTheme" parent="android:Theme.Material">
<item name ="android:color/primary">@color/primary</item>
<item name ="android:color/primaryDark">@color/primary_dark</item>
<item name ="android:colorAccent/primary">@color/accent</item>
</style>
<resource>

Default Styles & Themes


The Android platform provides a large collection of styles and themes that you can use in your
applications. You can find a reference of all available styles in the R.style class. To use the styles
listed here, replace all underscores in the style name with a period. For example, you can apply
the Theme_NoTitleBar theme with "@android:style/Theme.NoTitleBar". You can see the
following source code for Android styles and themes −
 Android Styles (styles.xml)
 Android Themes (themes.xml)

pg. 23
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

1.5 Android - Custom Components


Implementing own components in pre built-in components with extending subclass with own
defined class
Android offers a great list of pre-built widgets like Button, TextView, EditText, ListView,
CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc. which you can use
directly in your Android application development, but there may be a situation when you are not
satisfied with existing functionality of any of the available widgets. Android provides you with
means of creating your own custom components which you can customized to suit your needs.
If you only need to make small adjustments to an existing widget or layout, you can simply
subclass the widget or layout and override its methods which will give you precise control over
the appearance and function of a screen element.
This tutorial explains you how to create custom Views and use them in your application using
simple and easy steps.

Example of Custom Components in Custom View hierarchy


Creating a Simple Custom Component
Step Description

1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.tutorialspoint7.myapplication as
explained in the Hello World Example chapter.

pg. 24
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

2 Create an XML res/values/attrs.xml file to define new attributes along with their
data type.

3 Create src/mainactivity.java file and add the code to define your custom
component

4 Modify res/layout/activity_main.xml file and add the code to create Colour


compound view instance along with few default attributes and new attributes.

5 Run the application to launch Android emulator and verify the result of the
changes done in the application.

Create the following attributes file called attrs.xml in your res/values folder.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TimeView">
<declare-styleable name="TimeView">
<attr name="title" format="string" />
<attr name="setColor" format="boolean"/>
</declare-styleable>
</declare-styleable>
</resources>
Change the layout file used by the activity to the following.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<com.example.tutorialspoint7.myapplication.TimeView
android:id="@+id/timeView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:title="my time view"
custom:setColor="true" />

<TextView
android:layout_width="match_parent"

pg. 25
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

android:layout_height="wrap_content"
android:id="@+id/simple"
android:layout_below="@id/timeView"
android:layout_marginTop="10dp" />
</RelativeLayout>
Create the following java file called timeview for your compound view.
package com.example.tutorialspoint7.myapplication;
/**
* Created by TutorialsPoint7 on 9/14/2016.
*/
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.content.res.TypedArray;

import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimeView extends TextView {


private String titleText;
private boolean color;

public TimeView(Context context) {


super(context);
setTimeView();
}

public TimeView(Context context, AttributeSet attrs) {


super(context, attrs);
// retrieved values correspond to the positions of the attributes
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.TimeView);
int count = typedArray.getIndexCount();
try{

for (int i = 0; i < count; ++i) {

int attr = typedArray.getIndex(i);


// the attr corresponds to the title attribute
if(attr == R.styleable.TimeView_title) {

// set the text from the layout


titleText = typedArray.getString(attr);

pg. 26
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

setTimeView();
} else if(attr == R.styleable.TimeView_setColor) {
// set the color of the attr "setColor"
color = typedArray.getBoolean(attr, false);
decorateText();
}
}
}

// the recycle() will be executed obligatorily


finally {
// for reuse
typedArray.recycle();
}
}

public TimeView(Context context, AttributeSet attrs, int defStyle) {


super(context, attrs, defStyle);
setTimeView();
}

private void setTimeView() {


// has the format hour.minuits am/pm
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
String time = dateFormat.format(Calendar.getInstance().getTime());

if(this.titleText != null )
setText(this.titleText+" "+time);
else
setText(time);
}

private void decorateText() {


// when we set setColor attribute to true in the XML layout
if(this.color == true){
// set the characteristics and the color of the shadow
setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));
setBackgroundColor(Color.CYAN);
} else {
setBackgroundColor(Color.RED);
}
}
}

pg. 27
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Change your Main activity java file to the following code and run your application.
package com.example.tutorialspoint7.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView simpleText = (TextView) findViewById(R.id.simple);


simpleText.setText("That is a simple TextView");
}
}
The running application should look like the following screen shot.

pg. 28
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

1.6 Multichannel User Interfaces

Applicability parameters allow a model to use multiple UIs, each targeted to a different channel
of use.

Applicability helps you present the UI that's most appropriate to the context.

 You may need to configure the same model in multiple host applications, each having
different UI requirements.
o Host application A is used by self-service customers with elementary knowledge
of your product line. You might need to present a simplified UI for Product X that
guides the user through each step of the configuration, and hides some product
details that might be confusing.
o Host application B is used by internal sales fulfillment staff who are very familiar
with your product line. You might need to present a full-featured UI for Product
X that exposes every option, in a layout that enables users to reach those options
most efficiently.
 You may need to present the same product to the same type of audience, but in different
countries. Consequently you need to present the UI in multiple languages.

To provide for such multiple requirements, you can set the applicability parameters for a UI.

Setting Applicability Parameters

On the Overview tab for the UI, you can choose the applications and languages for which your
user interface is applicable.

1. Edit your configurator model and navigate to the Overview subtab of the User Interfaces
tab.
2. Under Applicability, select a parameter:
o Applications sets the applications that the UI will be used for. For example, if
you select Order Management, then the UI will be presented when Configurator
is invoked by Oracle Fusion Order Management.
o Languages sets the languages that the UI will be used for.For example, if you
select Korean and American English, then the UI will be presented when
Configurator is invoked by applications using one of those languages.
3. The default setting for each parameter is All, meaning that the UI is available at run time
to all channels.
4. Select the Selected setting. The Select button becomes enabled.
By default, the currently selected parameter is None. If you leave the setting as None,
then the UI will not be available at run time to any of that parameter's options. If no UIs
are available, then the default UI is used.

pg. 29
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

5. Click the Select button. The selection dialog box for the parameter presents a list of
available options, from which you select one or more to determine the applicability of the
UI.
6. If more than one UI has the same applicability parameter settings, then the sequence of
UIs in the table on the User Interfaces tab determines which UI will be used at run time.
To change the sequence in the table of UIs, select a UI then select one of
the Move commands on the Actions menu.
1.7 GESTURE BASED UI

Tapping, swiping, dragging, long-pressing – these are but a few of the gestures that have come to
dominate our digital experiences. Touch screen iPhones mainstreamed mobile gestures years
ago, and we haven‟t looked back since.
Gestures affect how we interact with interfaces, including phones, laptops and iPads. But we
don‟t have to look far to find a gestural interface beyond our work and entertainment devices.
It‟s no longer uncommon to use gestures when interacting with car screens or bathroom sinks.
Natural User Interfaces (NUIs) are so natural to users that the interface feels, and sometimes is,
invisible, like a touch screen interface. Some NUIs even use gesture control, allowing users to
interact with the interface without direct physical contact. BMW recently released a gesture
control feature that gives users touchless control over car volume, calls and more.
Gestures are growing more common in user interface design and play increasingly complex roles
in our everyday lives.
As technology advances, UX and UI designers and businesses will need to adapt. You don‟t have
to know all the technological intricacies or have an in-depth knowledge of computer intelligence.
Still, you should have a basic understanding of the capabilities, functions and best design
practices for gesture technology.

pg. 30
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

What Makes a Good Gesture


So, what are gestures?
Gestures are a way of communicating. We‟ve long used hand gestures and head nods to help
convey meaning, and now, gestures play a role in communicating with user interfaces.
Good gestures provide effective, efficient communication that aligns with our way of thinking.
Our thoughts and knowledge influence how we speak, and they influence our use of gestures,
especially in UI design. Consider how much easier it is for younger generations who grow up
around modern technology to pick up on gestures – or how the act of swiping mimics pushing or
wiping something away. It‟s why understanding your users is essential, even in gesture design.
Gestures cross the barrier between the physical and digital realms, allowing us to interact with
digital media with our bodies. In some ways, it makes using digital applications more fun, but
this isn‟t enough to make a gesture a good one.
A good motion gesture improves usability by making applications easier to use in all contexts.
Well-designed gestures have a shorter learning curve because they feel natural and are easy to
pick up on. To quote Bill Gates:
“Until now, we have always had to adapt to the limits of technology and conform the way we
work with computers to a set of arbitrary conventions and procedures. With NUI, computing
devices will adapt to our needs and preferences for the first time and humans will begin to use
technology in whatever way is most comfortable and natural for us.”
Benefits of Gesture Technology
The wide use of gestural interfaces is due to the many benefits that come with them. Three of the
most significant benefits of gestures are cleaner interfaces, ease of use and improved task
completion.
1. Cleaner Interfaces
Humans consume more content than ever before, businesses use more data and technology
continues to provide more services. With this increase in content, it‟s easy for interfaces and
displays to appear cluttered. Designers can use gestures to reduce the number of visual elements,
like buttons, that take up space.
2. Ease of Use
As discussed above, interactions become more natural with a gesture-based interface. The ease
of simple hand gestures allows us to use technology with minimal effort at maximum speed.
3. Improved Task Completion
Task completion rates and conversion rates increase when there‟s less a user has to do to
complete a task. You‟re more likely to finish a task when it takes less effort. A gesture-based
user interface capitalizes on this by making tasks simple and quick. They can even reduce the
number of steps it takes to complete a task.
Types of Gestures in UI Design
Design for touch has led to the development of many types of gestures, the most common of
which are tapping and swiping. There are three categories of gesture:
1. Navigational gestures (to navigate)
2. Action gestures (to take action)
3. Transform gestures (to manipulate content)
The following are some of the most common gestures across interfaces that all (or almost all) of
users are familiar with – even if not consciously. We mention screens, but you can substitute the
screen for a touchpad or any other gesture interface.

pg. 31
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Tap
A tap gesture is when you tap on the screen with one finger to open or select something, like an
app or page. Here‟s a tip: Design clickable interface elements so that the entire box or row is
clickable – not just the text. Giving users more space increases usability.
Double-Tap
Double-tapping is when you tap the screen twice in a row in close succession. Many applications
use this gesture to zoom in, but on Instagram, users can double-tap a photo to like it.
Swipe
Swiping involves moving your finger across the screen in one direction, touching down on one
side and lifting your finger on the other. Swipe gestures are often used for scrolling or switching
between pages. Tinder uses swiping right to match with a profile and swiping left to pass over
one.
Multiple-Finger Swipe
You can also conduct a swipe gesture with two or three fingers. This is a common feature on
laptop touchpads that use two- and three-finger swipes for different actions.
Drag
Dragging uses the same general motion as a swipe, only you move your finger slower and don‟t
lift it until you‟ve pulled the object to where you want it to be. You use dragging to move an
item to a new location, like when re-organizing your phone apps.
Fling
Like swiping, a fling gesture is when you move your finger across the screen at a high speed.
Unlike a drag, your finger doesn‟t remain in contact with an element. Flings are often used to
remove something from view.
Long Press
A long press is when you tap the screen but hold your finger down for longer than usual. Long
presses open up menu options, like when you hold text to copy it or hold down an app to delete
it.
Pinch
One of many two-finger gestures, a pinch is when you hold two fingers apart on the screen and
then drag them towards each other in a pinching motion. Pinch gestures are often used to zoom
back out after zooming in. Sometimes they present a view of all your open screens for navigation
purposes.
Pinch-Open or Spread
A pinch-open or spread gesture is the opposite of a pinch. You hold your two fingers down close
together and then spread them apart. Spreading, like double-tapping, is generally used to zoom
in.
Rotation
To do a rotation, press on the screen with two fingers and rotate them in a circular motion. The
best example of rotation is when you turn the map on Google Maps to see what‟s around you.
Gestures have been around for a while, so for most gestures, general guidelines exist.
And in most cases, there are rules you‟ll want to follow when designing gestures for an interface.
When creating an app, for example, you‟ll need to consider which interfaces users will use your
app on. There is the chance that users will download your app on Android and Apple phones,
both of which already use product-specific gestures. You‟ll need to evaluate the gestures of your

pg. 32
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

product‟s interfaces and decide how you‟ll take advantage of them or if it‟s worth it to add
gestures users are not familiar with.

Here are some handy gesture and motion guidelines for popular product interfaces.
 Google Gesture Guidelines
 Microsoft Gesture Guidelines
 Apple Gesture Guidelines
 Android Gesture Guidelines
When designing gesture-based user interfaces, it‟s good practice to stick with what users know.
You can get creative if it‟s called for, but a level of consistency among gestures and interfaces
helps keep them intuitive to users, increasing the usability of your product.
If you think a new gesture is in store, you need to test it extensively before implementing it.
You‟ll conduct a series of user research methods to test the usability, effectiveness, learning
curves and user satisfaction with a gesture before releasing it to the public.
You have the option to reuse a well-known gesture for a different purpose, but again, you should
test the effectiveness of this strategy in advance. The benefit here is that users are at least
familiar with the motion.
Take, for example, Instagram‟s use of the double-tap to like or “heart” a post. A double-tap is
usually used to zoom in, but it works well for Instagram‟s purpose. It‟s also a great study in
efficiency: Tapping the heart below a post requires one less tap but more aim. The alternative
double-tap method allows users to scroll faster since they have the whole image to aim for, and
it‟s intuitive to tap the object you‟re liking.
Designers have begun to develop a design language with hands, circles and arrows for
communicating gesture intent to product developers and strategists. This language is near
universal with minimal deviation.

Think Outside the Screen


Gestures exist in everyday scenarios outside of phone and laptop use. A growing number of
public restrooms have installed motion-sensitive sinks, air dryers and paper towel dispensers.
These devices also prevent the spread of germs – a nifty trait during flu season. Meanwhile, self-

pg. 33
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

driving cars are being enforced with gesture recognition technology to improve their
effectiveness and safety.
But you can still get creative with phone gestures while thinking outside of the screen. Devices
have been using rotation and shaking as methods of interaction for years now.
For example, Apple‟s „Shake to Undo‟ gives users the option to undo an action by shaking their
phone. And by now, you‟re probably familiar with rotating screens horizontally to watch a video
on full screen.
As long as they are tested first, creative gesture technologies can take products further and
increase usability.
Gestures and Accessibility
Gestures, like all things, should be accessible. Accessibility refers to making a product accessible
and usable to all people in all contexts, including people with disabilities. Gestures should adhere
to accessible design best practices to contribute to an equal environment, comply with the
Americans With Disabilities Act (ADA) and allow everyone who could benefit from your
product to use it.
Outside of making sure interface gestures are accessible, it‟s worth considering how you can use
gestures to improve accessibility. Apple realized that the iPhone‟s flat, textureless screens
presented an obstacle to blind users. So, they used their gesture-based interface to create
additional accessibility-based gestures that help the visually impaired use their products.
Don’t Forget UX
It‟s common to use the terms UX and UI interchangeably, but this is an inaccurate practice. UX
stands for user experience, and it deals with the user‟s perceptions and emotions while engaging
with a product. UI stands for user interface and involves the elements of a product a user
interacts with. UI is an important element of UX design. If you‟re interested in learning more
about each and their differences, check out our guide on UX vs UI Design.
The point here is that UX and UI are different, but it‟s critical to consider user experience when
designing interfaces. UI gestures that are fun but unhelpful or interesting but have poor usability
are a result of designers and developers who forgot about UX.
No matter how much testing you did, give users the option to remove certain gesture features.
Tapping is a vital touch screen gesture that everyone is familiar with, but some gestures aren‟t
crucial to a product‟s functioning and exist only to make it more usable. Sometimes, gestures
like these annoy users who aren‟t familiar with them or trigger the gesture without meaning to.
For example, on a Mac, swiping two fingers left or right on the touchpad sends a web browser
back or forward a page. Many users make this gesture by accident and are frustrated when the
page keeps changing. So, Apple gives users the option to disable this feature and many others.
Refine User Onboarding
User onboarding improves the successful use of a product by teaching users how to use it. Think
about a new program that, upon opening for the first time, guides you through all the functions or
steps to use it.
User onboarding is important for touch gestures because they‟re often hidden and easy to miss,
especially if a user isn‟t familiar with a gesture or doesn‟t have experience with it in that context.
If they don‟t know that they can use it or how to use it, they won‟t.
When onboarding a user, you want to be brief, teach one thing at a time and follow the learning
curve proven to work best in testing. Long tutorials and step-by-step lists are boring, less
interactive and often get skipped.

pg. 34
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

Embrace the Future of Gesture Interfaces


Gestures are already here. They exist in the present, making themselves useful in our everyday
lives. For users, these gestures can live in their subconscious as they swipe and double-tap along
without a thought. Product designers, developers and strategists have to understand gestures on a
more intimate level.

1.8 Layout of Screen Elements

The elements that constitute a Screen can be Data Elements, labels, or Screens. You call them
and specify their display characteristics in the Screen layout.

About this task


To define the Screen elements, you must complete the following tasks:
Procedure

1. Open the -CE Lines tab of a Screen.


2. If necessary, add a category in the table. When it is created, a Screen contains the top
category only. The top category line is not displayed in the tree by default but if you do
not specify any other category, all the Screen elements are inserted in this category. To
add a repetitive or a bottom category, click Add a category or select this action in the
contextual menu. Indicate the call values directly in the table or in the Category
definition section that opens.
3. Place your cursor in the adequate category in the tree, on the line after which you want to
insert a new element.
4. You can then add one of the following elements:
a. A Data Element. To do so, click Add Data Element or select this action in the
contextual menu. The selection wizard opens.

This wizard displays the three Data Element formats in the following order:
internal format, input format, and output format.

You can select contiguous instances in the selection wizard. To select


noncontiguous instances, select Multi-selection. Select each instance, with the
help of the filtering pattern if necessary. Then, click Add to selection list. You
can also double-click each instance to add it to the list. To remove an instance
from the selection list, select the instance in the selection list and click Remove
from selection list before you close the selection wizard.

Select one or more Data Elements and click OK. Indicate the call values directly
in the table or in the Field definition section. When a field is inserted, you can
add controls to it (such as presence check, validation conditions, update option).
To do so, select a field (a Data Element) in the tree and click Add additional
controls for the field or select this action in the contextual menu. Indicate the call
values directly in the table or in the Additional controls for the field section that
opens.

pg. 35
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2

b. A label. To do so, click Add Label or select this action in the contextual menu.
Indicate the call values directly in the table or in the Label definition section that
opens up.
c. A Screen call. To do so, click Add Screen element or select this action in the
contextual menu. Select a Screen in the selection wizard and indicate the call
values directly in the table or in the Screen call definition section.

1.9 What Does Voice XML Mean?

Voice XML is an Extensible Markup Language (XML) standard for storing and processing
digitized voice, input recognition and defining human and machine voice interaction. Voice
XML uses voice as an input to a machine for desired processing, thereby facilitating voice
application development. A voice-based application is managed by a voice browser.

Voice XML
Voice XML is developed as a standard markup language for delivering and processing voice
dialogs. Voice XML applications include automated driving assistance, voice access to email,
voice directory access and other services. Voice XML pages are transported online via the HTTP
protocol.

There are two basic Voice XML file types:

 Static: Hard coded by the application developer


 Dynamic: Generated by the server in response to client requests.

Voice XML architecture is based on the following components:

 Document server: Like a server that accepts client requests and generates appropriate
response post processing
 Voice XML interpreter subsystem: Processes request response output generated by the
document server.
 Implementation platform: Generates actions in response to user input
 Voice XML goals: Integrates voice-based services with Web applications for efficiency

Voice XML facilitates the following:

 Reduces client/server interactions by specifying multiple interactions per document


 Shields developers from low level implementation platform details
 Focuses on clear separation of business logic and interaction code
 Functions and delivers the same results, regardless of underlying implementation
platform
 Creates and processes simple dialogs. Complex dialogs may be constructed and
maintained with the help of Voice XML language tools.

pg. 36
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204_Mobile Application Development Unit-3

Memory Management – Design Patterns for Limited Memory – Workflow for Application
development – Java API – Dynamic Linking – Plugins and rule of thumb for using DLLs –
Multithreading in Java - Concurrency and Resource Management.
What do you understand by the Memory Management?
Android uses paging and mmap instead of providing swap space, which means any
memory your application touches cannot be paged out unless you release all references.
The Dalvik* Virtual Machine‘s heap size for application processes is limited.
Applications start up with 2 MB, and the maximum allocation, marked as ―largeHeap,‖ is
limited to 36 MB (depending on the specific device configuration). Examples of large heap
applications are Photo/Video Editor, Camera, Gallery, and Home Screen.
Android stores background application processes in an LRU cache. When the system
runs low on memory, it will kill processes according to the LRU strategy, but it will also
consider which application is the largest memory consumer. Currently, the maximum
background process count is 20 (depending on the specific device configuration). If you need
your app to live longer in the background, de-allocate unnecessary memory before moving to the
background and the Android system will be less likely to generate an error message or even
terminate the app.
Write a short note on Garbage Collection.
A managed memory environment, like the ART or Dalvik virtual machine, keeps track
of each memory allocation. Once it determines that a piece of memory is no longer being used
by the program, it frees it back to the heap, without any intervention from the programmer. The
mechanism for reclaiming unused memory within a managed memory environment is known
as garbage collection. Garbage collection has two goals: find data objects in a program that
cannot be accessed in the future; and reclaim the resources used by those objects.
Android‘s memory heap is a generational one, meaning that there are different buckets of
allocations that it tracks, based on the expected life and size of an object being allocated. For
example, recently allocated objects belong in the Young generation. When an object stays active
long enough, it can be promoted to an older generation, followed by a permanent generation.
Each heap generation has its own dedicated upper limit on the amount of memory that
objects there can occupy. Any time a generation starts to fill up, the system executes a garbage
collection event in an attempt to free up memory. The duration of the garbage collection depends
on which generation of objects it‘s collecting and how many active objects are in each
generation.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 1


MC4204_Mobile Application Development Unit-3
Even though garbage collection can be quite fast, it can still affect your app‘s
performance. You don‘t generally control when a garbage collection event occurs from within
your code. The system has a running set of criteria for determining when to perform garbage
collection. When the criteria are satisfied, the system stops executing the process and begins
garbage collection. If garbage collection occurs in the middle of an intensive processing loop
like an animation or during music playback, it can increase processing time. This increase can
potentially push code execution in your app past the recommended 16ms threshold for efficient
and smooth frame rendering.
Define DDMS.
Android Studio includes a debugging tool called the Dalvik Debug Monitor Service
(DDMS). DDMS provides services like screen capture on the device, threading, heap
information on the device, logcat, processes, incoming calls, SMS checking, location, data
spoofing, and many other things related to testing your Android application.
DDMS connects the IDE to the applications running on the device. On Android, every
application runs in its own process, each of which hosts its own virtual machine (VM). And each
process listens for a debugger on a different port.
When it starts, DDMS connects to ADB (Android Debug Bridge, which is a command-
line utility included with Google‘s Android SDK.). An Android Debugger is used for debugging
the Android app and starts a device monitoring service between the two. This will notify DDMS
when a device is connected or disconnected. When a device is connected, a VM monitoring
service is created between ADB and DDMS, which will notify DDMS when a VM on the device
is started or terminated.

What are the steps to Improve Memory Usage?


Android is a worldwide mobile platform and millions of Android developers are dedicated to
building stable and scalable applications. Here is a list of tips and best practices for improving
memory usage in Android applications:
1. Be careful about using a design pattern with ―abstraction‖. Although from the point of
view of design pattern, abstraction can help to build more flexible software architect. In
the mobile world, abstraction may involve side effect for its extra code to be executed,
which will cost more time and memory. Unless abstraction can provide your application
a significant benefit, you would be better not to use it.
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 2
MC4204_Mobile Application Development Unit-3
2. Avoid using ―enum‖. Enum will double memory allocation than ordinary static constant,
so do not use it.
3. Try to use the optimized SparseArray, SparseBooleanArray, and LongSparseArray
containers instead of HashMap. HashMap allocates an entry object during every
mapping which is a memory inefficient action, also the low-performance behavior —
―autoboxing/unboxing‖ is spread all over the usage. Instead, SparseArray-like containers
map keys into a plain array. But please remember that these optimized containers are not
suitable for large numbers of items, when executing add/remove/search actions, they are
slower than Hashmap if your data set is over thousands of records.
4. Avoid creating unnecessary objects. Do not allocate memory especially for short-term
temporary objects if you can avoid it, and garbage collection will occur less when fewer
objects are created.
5. Check the available heap of your application. Invoke
ActivityManager::getMemoryClass() to query how many heap(MB) is available for your
application. OutofMemory Exception will occur if you try to allocate more memory than
is available. If your application declares a ―largeHeap‖ in AndroidManifest.xml, you can
invoke ActivityManager::getLargeMemoryClass() to query an estimated large heap size.
6. Coordinate with the system by implementing onTrimMemory() callback. Implement
ComponentCallbacks2::onTrimMemory(int) in your Activity/Service/ContentProvider to
gradually release memory according to latest system constraints. The
onTrimMemory(int) helps overall system response speed, but also keep your process
alive longer in the system.
7. When TRIM_MEMORY_UI_HIDDEN occurs, it means all the UI in your application
has been hidden and you need to free UI resources. When your application is foreground,
you may receive TRIM_MEMORY_RUNNING[MODERATE/LOW/CRITICAL], or in
the background, you may receive
TRIM_MEMORY_[BACKGROUND/MODERATE/COMPLETE]. You can free non-
critical resources based on the strategy to release memory when system memory is tight.
8. External libraries should be used carefully. External libraries are often written for a non-
mobile device and can be inefficient in Android. You must take into account the effort in
porting and optimizing the library for mobile before you decide to use it. If you are using
a library for only one or two features from its thousands of other uses, it may be best to
implement it by yourself.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 3


MC4204_Mobile Application Development Unit-3
9. Services should be used with caution. If you need a service to run a job in the
background, avoid keeping it running unless it‘s actively performing a task. Try to
shorten its lifespan by using an IntentService, which will finish itself when it‘s done
handling the intent. Services should be used with the caution to never leave one running
when it‘s not needed. Worst case, the overall system performance will be poor and users
will find your app and uninstall it (if possible).
10. But if you are building an app that needs to run for a long period of time, e.g., a music
player
service, you should split it into two processes: one for the UI and the other for the
background service by setting the property ―android:process‖ for your Service in
AndroidManifest.xml. The resources in the UI process can be released after hidden,
while the background playback service is still running. Keep in mind that the background
service process MUST NOT touch any UI; otherwise, the memory allocation will be
doubled or tripled!
How to Avoid Memory Leaks?
Use memory carefully with above tips can bring benefit for your application incrementally, and
make your application stay longer in the system. But all benefit will be lost if memory leakage
happens. Here is some familiar potential leakage that developer needs to keep in mind.
1. Remember to close the cursor after querying the database. If you want to keep the cursor
open long-term, you must use it carefully and close it as soon as the database task
finished.
2. Remember to call unregisterReceiver() after calling registerReceiver().
3. Avoid Context leakage. If you declare a static member variable ―Drawable‖ in your
Activity, and then call view.setBackground(drawable) in onCreate(), after screen rotate, a
new Activity instance will be created and the old Activity instance can never be de-
allocated because drawable has set the view as callback and view has a reference to
Activity (Context). A leaked Activity instance means a significant amount of memory,
which will cause OOM easily.
4. There are two ways to avoid this kind of leakage:
1. Do not keep long-lived references to a context-activity. A reference to an activity
should have the same life cycle as the activity itself.
2. Try using the context-application instead of a context-activity.
Be careful about using Threads. Threads in Java are garbage collection roots; that is, the Dalvik
Virtual Machine (DVM) keeps hard references to all active threads in the runtime system, and as

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 4


MC4204_Mobile Application Development Unit-3
a result, threads that are left running will never be eligible for garbage collection. Java threads
will persist until either they are explicitly closed or the entire process is killed by the Android
system. Instead, the Android application framework provides many classes designed to make
background threading easier for developers:
 Use Loader instead of a thread for performing short-lived asynchronous background
queries in conjunction with the Activity lifecycle.
 Use Service and report the results back to the Activity using a BroadcastReceiver.
 Use AsyncTask for short-lived operations.
Illustrate and explain the concept of Android Profiling Tools
Android Profiling Tool will help you in managing your memory on the Android device. The
Android SDK provides two ways of profiling app memory:
1. Using Allocation Tracker
2. Using Heap Dump
Using Allocation Tracker
Allocation Tracker records each memory allocation that your application performs during the
profiling cycle. The Allocation Tracker is useful when you want to find out which type of
memory allocation is taking place. But it does not give you any information about the
application‘s heap which is the memory set aside for dynamic memory allocation.
The Allocation Tracker displays the memory allocation for the selected process. It shows the
specific objects that are being allocated along with the thread, method and the line code that
allocated them.
DDMS provides a feature to track objects that are being allocated to memory and to see which
classes and threads are allocating the objects. This allows you to track where the objects are
being allocated in real time when you perform certain actions in your application. This data is
valuable for measuring memory usage that can otherwise affect application performance.
Starting Allocation Tracker in Android DDMS
 Install your app in Android emulator or device. Click on Android button available at the
bottom of the Android Studio.
 Start allocation tracking.
 Play around with the app for some time.
 Stop allocation tracking.
Refer to the Figure below:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 5


MC4204_Mobile Application Development Unit-3

 After a few seconds, a pane with your recorded data opens.

Define Heap Dumps


A Heap Dump is a snapshot of an application‘s heap, which is stored in a binary format called
HPROF. The Dalvik virtual machine can produce a complete dump of the contents of the virtual
heap. This is very useful for debugging memory usage and looking for memory leaks.
Discuss in detail about various Design Patterns for Limited Memory.
Design Patterns are reusable solutions to common software problems. These goals span
from a single object all the way to the entire project and lead to patterns that fall into the
following categories:
 Creational patterns: How you create objects.
 Structural patterns: How you compose objects.
 Behavioral patterns: How you coordinate object interactions.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 6


MC4204_Mobile Application Development Unit-3
Design patterns usually deal with objects. They present a solution to a reoccurring problem that
an object shows and help eradicate design-specific problems. In other words, they represent
challenges, other developers already faced and prevent you from reinventing the wheel by
showing you proven ways to solve those problems.
You may use one or several of these patterns already without having ―A Capitalized Fancy
Name‖ for it. However, Future You will appreciate that you didn‘t leave design decisions to
intuition alone.
In the sections that follow, you‘ll cover these patterns from each category and see how they
apply to Android:

Creational Patterns

 Builder
 Dependency Injection
 Singleton
 Factory

Structural Patterns

 Adapter
 Facade
 Decorator
 Composite

Behavioral Patterns

 Command
 Observer
 Strategy
 State

Creational Patterns

“When I need a particularly complex object, how do I get an instance of it?” – Future You

Future You hopes the answer isn‘t ―Just copy and paste the same code every time you need an
instance of this object―. Instead, Creational patterns make object instantiation straightforward
and repeatable.

Builder

At a certain restaurant, you create your own sandwich: you choose the bread, ingredients and
condiments you‘d like on your sandwich from a checklist on a slip of paper. Even though the
checklist instructs you to build your own sandwich, you only fill out the form and hand it over
the counter. You don‘t build the sandwich, just customize and consume it. :]

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 7


MC4204_Mobile Application Development Unit-3
Similarly, the Builder pattern simplifies the creation of objects, like slicing bread and stacking
pickles, from its representation, a yummy sandwich. Thus, the same construction process can
create objects of the same class with different properties.

In Android, an example of the Builder pattern is AlertDialog.Builder:

Aler

This builder proceeds step-by-step and lets you specify only the parts of AlertDialog that you need
to specify. Take a look at the AlertDialog.Builder documentation. You‘ll see there are quite a few
commands to choose from when building your alert.

The code block above produces the following alert:

A different set of choices would result in a completely different sandwich– er, alert. :]

Dependency Injection

Dependency injection is like moving into a furnished apartment. Everything you need is
already there. You don‘t have to wait for furniture delivery or follow pages of IKEA instructions
to put together a Borgsjö bookshelf.

In software terms, dependency injection has you provide any required objects to instantiate a
new object. This new object doesn‘t need to construct or customize the objects themselves.

In Android, you might find you need to access the same complex objects from various points in
your app, such as a network client, image loader or SharedPreferences for local storage. You
can inject these objects into your activities and fragments and access them right away.

Currently, there are three main libraries for dependency injection: Dagger ‗2‘, Dagger Hilt,
and Koin. Let‘s take a look at an example with Dagger. In it you annotate a class
with @Module, and populate it with @Provides methods like:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 8


MC4204_Mobile Application Development Unit-3

The module above creates and configures all required objects. As an additional best practice in
larger apps, you could create multiple modules separated by function.

Then, you make a Component interface to list your modules and the classes you‘ll inject:

The component ties together where the dependencies are coming from, the modules, and where
they‘re going to, the injection points.

Finally, you use the @Inject annotation to request the dependency wherever you need it, along
with lateinit to initialize a non-nullable property after you create the containing object

This pattern may seem complicated and magical at first, but it can help simplify your activities
and fragments.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 9


MC4204_Mobile Application Development Unit-3
Singleton

The Singleton pattern specifies that only a single instance of a class should exist with a global
access point. This pattern works well when modeling real-world objects with only one instance.
For example, if you have an object that makes network or database connections, having more
than one instance of the project may cause problems and mix data. That‘s why in some scenarios
you want to restrict the creation of more than one instance.

The Kotlin object keyword declares a singleton without needing to specify a static instance like
in other languages:

When you need to access members of the singleton object, you make a call like this:

Behind the scenes, an INSTANCE static field backs the Kotlin object. So, if you need to use a
Kotlin object from Java code, you modify the call like this:

By using object, you‘ll know you‘re using the same instance of that class throughout your app.

The Singleton is probably the most straightforward pattern to understand initially but can be
dangerously easy to overuse and abuse. Since it‘s accessible from multiple objects, the singleton
can undergo unexpected side effects that are difficult to track down, which is exactly what
Future You doesn‘t want to deal with. It‘s important to understand the pattern, but other design
patterns may be safer and easier to maintain.

Factory

As the name suggests, Factory takes care of all the object creational logic. In this pattern, a
factory class controls which object to instantiate. Factory pattern comes in handy when dealing
with many common objects. You can use it where you might not want to specify a concrete
class.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 10


MC4204_Mobile Application Development Unit-3
Take a look at the code below for a better understanding:

// 1

interface HostingPackageInterface {

fun getServices(): List<String>

// 2

enum class HostingPackageType {

STANDARD,

PREMIUM

// 3

class StandardHostingPackage : HostingPackageInterface {

override fun getServices(): List<String> {

return ...

}}

// 4

class PremiumHostingPackage : HostingPackageInterface {

override fun getServices(): List<String> {

return ...

}}

// 5

object HostingPackageFactory {

// 6

fun getHostingFrom(type: HostingPackageType): HostingPackageInterface {

return when (type) {

HostingPackageType.STANDARD -> {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 11


MC4204_Mobile Application Development Unit-3
StandardHostingPackage()

HostingPackageType.PREMIUM -> {

PremiumHostingPackage()

} } }}

Here‘s a walk through the code:

1. This is a basic interface for all the hosting plans.


2. This enum specifies all the hosting package types.
3. StandardHostingPackage conforms to the interface and implements the required method to list
all the services.
4. PremiumHostingPackage conforms to the interface and implements the required method to list
all the services.
5. HostingPackageFactory is a singleton class with a helper method.
6. getHostingFrom inside HostingPackageFactory is responsible for creating all the objects.

You can use it like this:

val standardPackage =
HostingPackageFactory.getHostingFrom(HostingPackageType.STANDARD)

Structural Patterns

“So, when I open this class, how will I remember what’s it doing and how it’s put together?” –
Future You

Future You will undoubtedly appreciate the Structural Patterns you used to organize the guts of
your classes and objects into familiar arrangements that perform typical
tasks. Adapter and Facade are two commonly-seen patterns in Android.

Adapter
A famous scene in the movie Apollo 13 features a team of engineers tasked with fitting a square
peg into a round hole. This, metaphorically, is the role of an adapter. In software terms, this
pattern lets two incompatible classes work together by converting a class‘s interface into the
interface the client expects.
Consider your app‘s business logic. It might be a Product or a User or Tribble. It‘s the square
peg. Meanwhile, a RecyclerView is the same basic object across all Android apps. It‘s the

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 12


MC4204_Mobile Application Development Unit-3
round hole.
In this situation, you can use a subclass of RecyclerView.Adapter and implement the required
methods to make everything work:
class TribbleAdapter(private val tribbles: List<Tribble>) :
RecyclerView.Adapter<TribbleViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): TribbleViewHolder {
val inflater = LayoutInflater.from(viewGroup.context)
val view = inflater.inflate(R.layout.row_tribble, viewGroup, false)
return TribbleViewHolder(view)
}
override fun onBindViewHolder(viewHolder: TribbleViewHolder, itemIndex: Int) {
viewHolder.bind(tribbles[itemIndex])
}
override fun getItemCount() = tribbles.size
}
RecyclerView doesn‘t know what a Tribble is, as it‘s never seen a single episode of Star Trek,
not even the new movies. :] Instead, it‘s the adapter‘s job to handle the data and send
the bind command to the correct ViewHolder.

Facade
The Facade pattern provides a higher-level interface that makes a set of other interfaces
easier to use. The following diagram illustrates this idea in more detail:

If your Activity needs a list of books, it should be able to ask a single object for that list
without understanding the inner workings of your local storage, cache and API client. Beyond
keeping your Activities and Fragments code clean and concise, this lets Future You make any
required changes to the API implementation without impacting the Activity.
Square‘s Retrofit is an open-source Android library that helps you implement the Facade
pattern. You create an interface to provide API data to client classes like so:
interface
BooksApi {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 13


MC4204_Mobile Application Development Unit-3
@GET("book
s")

fun listBooks(): Call<List<Book>>

The client needs to call listBooks() to receive a list of Book objects in the callback. It‘s nice
and clean. For all it knows, you could have an army of Tribbles assembling the list and
sending it back via transporter beam. :]
This lets you make all types of customizations underneath without affecting the client. For
example, you can specify a customized JSON deserializer that the Activity has no clue about:
val retrofit = Retrofit.Builder()

.baseUrl("http://www.myexampleurl.com")

.addConverterFactory(GsonConverterFactory.create())

.build()

val api = retrofit.create<BooksApi>(BooksApi::class.java)

Decorator
The Decorator pattern dynamically attaches additional responsibilities to an object to
extended its functionality at runtime. Take a look at the example below:
//1

interface Salad {

fun getIngredient(): String

//2

class PlainSalad : Salad {

override fun getIngredient():


String {return "Arugula &
Lettuce"

//3

open class SaladDecorator(protected var salad: Salad) : Salad {override fun getIngredient():
String {
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 14
MC4204_Mobile Application Development Unit-3
return salad.getIngredient()

//4

class Cucumber(salad: Salad) :


SaladDecorator(salad) {override fun
getIngredient(): String {

return salad.getIngredient() + ", Cucumber"

//5

class Carrot(salad: Salad) :


SaladDecorator(salad) {override fun
getIngredient(): String {

return salad.getIngredient() + ", Carrot"

Here‘s what the above code defines:


. A Salad interface helps with knowing the ingredients.

. Every salad needs a base. This base is Arugula & Lettuce thus, PlainSalad.

. A SaladDecorator helps add more toppings to the PlainSalad.

. Cumcumber inherts from SaladDecorator.

. Carrot inherts from SaladDecorator.

By using the SaladDecorator class, you can extend your salad easily without having to
change PlainSalad. You can also remove or add any salad decorator on runtime. Here‘s how
you use it:
val cucumberSalad = Cucumber(Carrot(PlainSalad()))
print(cucumberSalad.getIngredient()) // Arugula & Lettuce,
Carrot, Cucumberval carrotSalad = Carrot(PlainSalad())

print(carrotSalad.getIngredient()) // Arugula & Lettuce, Carrot

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 15


MC4204_Mobile Application Development Unit-3
Composite
You use the Composite pattern when you want to represent a tree-like structure consisting
of uniform objects. A Composite pattern can have two types of objects: composite and leaf.
A composite object can have further objects, whereas a leaf object is the last object.
Take a look at the following code to understand it better:
//1

interface Entity {

fun getEntityName(): String

//2

class Team(private val name: String) :


Entity {override fun getEntityName():
String {

return name

//3

class Raywenderlich(private val name: String) :


Entity {private val teamList =
arrayListOf<Entity>()

override fun getEntityName(): String {

return name + ", " + teamList.map { it.getEntityName() }.joinToString(", ")

fun addTeamMember(member: Entity) {


teamList.add(member)

In the code above you have:


. Component, an interface Entity in Composite pattern.

. A Team class implements an Entity. It‘s a Leaf.

. Raywenderlich also implements an Entity interface. It‘s a Composite.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 16


MC4204_Mobile Application Development Unit-3
Logically and technically the organization, in this case Raywenderlich, adds an Entity to the
Team. Here‘s how you use it:
val composite = Raywenderlich("Ray")

val ericTeamComposite =
Raywenderlich("Eric")val aaqib =
Team("Aaqib")

val vijay = Team("Vijay")


ericTeamComposite.addTeamMemb
er(aaqib)
ericTeamComposite.addTeamMemb
er(vijay)
composite.addTeamMember(ericTea
mComposite)
print(composite.getEntityName()) //
Ray, Eric, Aaqib, v ijay

Behavioral Patterns

“So… how do I tell which class is responsible for what?” – Future You

Behavioral Patterns let you assign responsibility for different app functions. Future You
can use them to navigate the project‘s structure and architecture.
These patterns can vary in scope, from the relationship between two objects to your
app‘s entire architecture. Often, developers use several behavioral patterns together in the
same app.

Command
When you order some Saag Paneer at an Indian restaurant, you don‘t know which cook
will prepare your dish. You just give your order to the waiter, who posts the order in the
kitchen for the next available cook.
Similarly, the Command pattern lets you issue requests without knowing the receiver. You
encapsulate a request as an object and send it off. Deciding how to complete the request is
an entirely separate mechanism.
Greenrobot‘s EventBus is a popular Android framework that supports this pattern in the
following manner:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 17


MC4204_Mobile Application Development Unit-3

An Event is a command-style object that‘s triggered by user input, server data or pretty much
anything else in your app. You can create specific subclasses which carry data as well:
class MySpecificEvent { /* Additional fields if needed */ }

After defining your event, you obtain an instance of EventBus and register an object as a
subscriber. For example, if you register an Activity you‘ll have:
override fun onStart() {
super.onStart()
EventBus.getDefault().re
gister(this)

override fun
onStop() {
super.onStop()

EventBus.getDefault().unregister(this)

Now that the object is a subscriber, tell it what type of event to subscribe to and what it
should do when it receives one:
@Subscribe(threadMode =
ThreadMode.MAIN)fun
onEvent(event:
MySpecificEvent?) {

/* Do something */

Finally, create and post one of those events based on your criteria:
EventBus.getDefault().post(MySpecificEvent())

Since so much of this pattern works its magic at run-time, Future You might have a little
trouble tracing this pattern unless you have good test coverage. Still, a well-designed
flow of commands balances out the readability and should be easy to follow later.

Observer
The Observer pattern defines a one-to-many dependency between objects. When one
object changes state, its dependents get a notification and updates automatically.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 18


MC4204_Mobile Application Development Unit-3
This pattern is versatile. You can use it for operations of indeterminate time, such as API
calls. You can also use it to respond to user input.
It was originally popularized by the RxAndroid framework, also known as Reactive
Android. This library lets you implement this pattern throughout your app:
apiService.getData(someData)

.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.subscribe (/* an Observer */)

In short, you define Observable objects that will emit values. These values can emit all at
once, as a continuous stream or at any rate and duration.
Subscriber objects will listen for these values and react to them as they arrive. For
example, you can open a subscription when you make an API call, listen to the server‘s
response and react accordingly.
More recently Android also introduced a native way to implement this pattern through
LiveData. You can learn more about this topic here.

Strategy
You use a Strategy pattern when you have multiple objects of the same nature with
different functionalities. For a better understanding, take a look at the following code:
// 1

interface
TransportTypeStrategy
{fun travelMode():
String

// 2

class Car :
TransportTypeStrategy {
override fun travelMode():
String {

return "Road"

class Ship :
TransportTypeStrategy {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 19


MC4204_Mobile Application Development Unit-3
override fun travelMode():
String {

return "Sea"

class Aeroplane :
TransportTypeStrategy {
override fun travelMode():
String {

return "Air"

// 3

class TravellingClient(var strategy:


TransportTypeStrategy) {fun update(strategy:
TransportTypeStrategy) {

this.strategy = strategy

fun howToTravel(): String {

return "Travel by ${strategy.travelMode()}"

Here‘s a code breakdown:


. A Transport Type Strategy interface has a common type for other strategies so it can be
interchanged at runtime. . All the concrete classes conform to Transport Type Strategy.

. Travelling Client composes strategy and uses its functionalities inside the functions exposed
to the client side.

Here‘s how you use it:


val travelClient = TravellingClient(Aeroplane())
print(travelClient.howToTravel()) // Travel by Air

// Change the Strategy to Ship


travelClient.update(Ship())
print(travelClient.howToTravel()) // Travel
by Sea

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 20


MC4204_Mobile Application Development Unit-3
State
In the State pattern, the state of an object alters its behavior accordingly when the internal
state of the object changes. Take a look at the following snippets:
// 1

interface
PrinterState {
fun print()

// 2

class Ready :
PrinterState {override
fun print() {

print("Printed Successfully.")

// 3

class NoInk :
PrinterState {override
fun print() {

print("Printer doesn't have ink.")

// 4

class Printer() {

private val noInk =


NoInk() private val
ready = Ready()
private var state:
PrinterStateprivate var
ink = 2

init {

state = ready

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 21


MC4204_Mobile Application Development Unit-3

private fun setPrinterState(state: PrinterState) {


this.state = state

// 5

fun
startPrint
ing() {
ink--

if (ink >= 0) {
setPrinterState(rea
dy)

} else {
setPrinterState(n
oInk)

state.print()

// 6

fun
installIn
k() {ink
=2

print("Ink installed.")

Here‘s a code breakdown:


. PrinterState defines the states of a printer.

. Ready is a concrete class implementing PrinterState to define a ready state of the printer.

. NoInk is a concrete class implementing PrinterState to define that the printer has no ink.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 22


MC4204_Mobile Application Development Unit-3
. Printer handler does all the printing.

. startPrinting starts printing.

. installInk installs ink.

Here‘s how you use it:


val printing = Printer()

printing.startPrinting() // Printed Successfully.


printing.startPrinting() // Printed Successfully.
printing.startPrinting() // Printer doesn't have ink.
printing.installInk() // Ink installed.
printing.startPrinting() // Printed Successfully.

So, you create an object of the class Printer to print. The Printer class handles all the states of
the printer internally. It‘s either on a Ready state or in a NoInk state.
Explain in detail about the Workflow for Application development
A workflow application is a software tool that automates the tasks involved in a business process.
The workflow application routes data along a predefined path until an item in the process is
completed. Tasks in the workflow may include approvals, adding information, or data transfers.

Workflow applications can be standalone apps that exist on their own or built on a platform where

endless numbers of applications reside. Workflow applications help business owners to automate

their mundane business processes.

Workflow apps will break a workflow down into a set of data needed to complete the process, and a

path for the data to follow. The workflow application will use a form to collect data at different

points in the process.

The workflow to develop an app for Android is conceptually the same as other app
platforms. However, to efficiently build a well-designed app for Android, you need some
specialized tools. The following list provides an overview of the process to build an Android app
and includes links to some Android Studio tools you should use during each phase of
development.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 23


MC4204_Mobile Application Development Unit-3

1. Set up your workspace


This is the phase you probably already finished: Install Android Studio and create a project.
For a walkthrough with Android Studio that teaches some Android development fundamentals,
also check out the guide to Building your first app.
2. Write your app
Now you can get to work. Android Studio includes a variety of tools and intelligence to help you
work faster, write quality code, design a UI, and create resources for different device types. For
more information about the tools and features available, see Write your app.
3. Build and run
During this phase, you build your project into a debuggable APK package that you can install
and run on the emulator or an Android-powered device. For more information about how to run
your code, see Build and run your app.
You can also begin customizing your build. For example, you can create build variants that
produce different versions of your app from the same project, and shrink your code and
resources to make your app smaller. For an introduction to customizing your build,
see Configure your build.
4. Debug, profile, and test
This is the iterative phase in which you continue writing your app but with a focus on
eliminating bugs and optimizing app performance. Of course, creating tests will help you in
those endeavors.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 24


MC4204_Mobile Application Development Unit-3
Publish
When you're ready to release your app to users, there are just a few more things to
consider, such as versioning your app, building an Android App Bundle, and signing it
with a key. For more information, see the Publish your app.
What do you understand by JAVA API
An API can be described as a way to enable computers to possess a common interface, to allow
them to communicate with each other. Java Application Programming Interface (API) is the area
of Java development kit (JDK). An API includes classes, interfaces, packages and also their
methods, fields, and constructors.
All these built-in classes give benefits to the programmer. Only programmers understand how to
apply that class. A user interface offers the basic user interaction between user and computer; in
the same manner, the API works as an application program interface that gives connection
amongst the software as well as the consumer. API includes classes and packages which usually
assist a programmer in minimizing the lines of a program.
Understanding API in Java
API in Java 1
Java Development Kit (JDK) is usually made up of three fundamental components, as per
below:
1. Java compiler
2. Java Virtual Machine (JVM)
3. Java Application Programming Interface (API)
The Java API added to the JDK explains the function of every element. In Java programming,
several components are pre-created as well as widely used.
Hence, the programmer can make use of a prewritten program with the Java API. After
mentioning the obtainable API classes as well as packages, the programmer quickly creates the
required program classes and packages to get executed.
The Java API is a vital element of the JDK and identifies features of every element. Although
Programming in Java, the component is already produced and done it. Through Java, the API
coder can simply make use of the pre-written program.
The programmers initially declare the classes and packages; then, this coder can simply use the
application program of classes and packages to get executed.
Working with API in Java
The JAX-RS (Java API for Restful Web Services) Client provides the following capabilities:
Invoke REST endpoints

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 25


MC4204_Mobile Application Development Unit-3
Use similar paths/templates as server API
Improved async invoker support
Server-sent Events support
Representational State Transfer or REST is a web standards-based architectures and uses HTTP
Protocol for data communication.
HTTP methods are most commonly used in REST-based architectures like getting, PUT,
DELETE and POST.
Advantages of API in Java

Extensive SQL Support


APIs in Java enable a wide range of SQL support services in user applications through a
component-based interface.
Application
APIs in Java provide effortless access to all of an application‘s major software components and
easily deliver services.
Efficiency
Java APIs are highly efficient because they enable rapid application deployment. Also, the data
that the application generates is always available online.
Automation
APIs allow computers to automatically upload, download, update and delete data automatically
without human interaction.
Integration
Java APIs can integrate into any application and website and provide a fluid user experience
with dynamic data delivery.
Scope
Java APIs easily make websites, applications, and information available to a wide range of users
and audiences.
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 26
MC4204_Mobile Application Development Unit-3
Customization
Java APIs enable developers and businesses to build applications that personalize the user
interface and data.
Adaptability
Java APIs are highly flexible and adaptable because they can easily accept feature updates and
changes to frameworks and operating environments.
Explain the various Types of Java APIs.
There are four types of APIs in Java:
 Public
 Private
 Partner
 Composite

Public
Public (or open) APIs are Java APIs that come with the JDK. They do not have strict restrictions
about how developers use them.
Private
Private (or internal) APIs are developed by a specific organization and are accessible to only
employees who work for that organization.
Partner
Partner APIs are considered to be third-party APIs and are developed by organizations for
strategic business operations.
Composite
Composite APIs are microservices, and developers build them by combining several service
APIs.
Now that we‘ve covered the types of Java APIs, let‘s discuss the categorization of Java APIs
based on the services that different varieties of APIs in Java provide.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 27


MC4204_Mobile Application Development Unit-3
What are the services performed in JAVA API. Explain in detail
Data and API Services
Data and API services are another way to categorize Java APIs other than public, private,
partner, and composite. APIs are also classified based on their data-manipulation capabilities
and the variety of services they offer, including:
 Internal API services
 External API services
 CRUD
 User interface services
Internal API Services
Internal API services are developed to offer organizations services specific to that organization.
These services include only complex data operations and internal processes.
External API Services
External APIs are open-source APIs that developers integrate into an existing application or
website.
CRUD
CRUD APIs provide data manipulation operations over various data storage units such as
software as a service (SaaS) and relational database management systems (RDBMS), using
standard storage-unit connecting tools like Java Database Connectivity (JDBC).
User Interface Services
User interface service APIs are open-source APIs that allow developers to build user interfaces
for mobile devices, computers, and other electronics.
API Service Protocols
The rules and protocols guide the functionality of the Java API. Different APIs have different
service protocols. Let‘s consider an example of RESTful API service protocol as an example.
For a typical RESTful API, developers must follow these rules:
Stateless
Uniform interface
Client-server
Cache
Layered
Stateless
A RESTful API follows client-server architecture so it must be stateless.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 28


MC4204_Mobile Application Development Unit-3
Uniform Interface
The entities in a RESTful API are the server and clients. Applications that run on a global scale
need a uniform client and server interface through the Hypertext Transfer Protocol (HTTP).
Uniform Resource Identifiers (URIs) allocate the required resources.
Client-Server
The client-server model used in the RESTful API should be fault-tolerant. Both the client and
server are expected to operate independently. The changes made at the client end should not
affect the server end and vice versa.
Cache
Including a cache memory allows the application to record intermediate responses and run faster
in real-time. A RESTful API also includes the cache memory.
Layered
A RESTful API is built using layers. Layers in the API are loosely coupled, or independent,
from each other. Each layer contributes to a different level of hierarchy and also supports
encapsulation..

Dynamic Linking
What is dynamic linking?
Dynamic linking means that the code for some external routines is located and loaded when
the program is first run. When you compile a program that uses shared libraries, the shared
libraries are dynamically linked to your program by default.
Dynamically linked programs take up less disk space and less virtual memory if more
than one program uses the routines in the shared libraries.
Static linking copies all the libraries required for the program into the final executable file.
The linker performs this task, and it is the last step of compilation. The linker combines the
relevant libraries with the program code to resolve external references. Finally, the linker
generates an executable file suitable for loading into memory. The final statistically linked file
contains the calling program and called programs. Generally, these files are large because they
are connected with other files.
In dynamic linking, the names of the external libraries /shared libraries are copied into the final
executable; thus, the real linking occurs at run time when the executable file and libraries load to the
memory. The operating system performs dynamic linking. Generally, there is only one copy of a shared
library is in the memory. Therefore, the size of the executable file is lower. It is possible to update and

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 29


MC4204_Mobile Application Development Unit-3
recompile the external libraries. Moreover, if the shared library code is already available in memory,
there will be less load time.
Difference Between Static and Dynamic Linking
Static linking is the process of copying all library modules used in the program into the final
executable image. In contrast, dynamic linking is the process of loading the external shared
libraries into the program and then binds those shared libraries dynamically to the program.
Thus, this is the main difference between static linking and dynamic linking.
Occurrence
Moreover, static linking is the last step of compilation, while dynamic linking occurs at run
time.
File size
While statistically linked files are larger in size, dynamically linked files are smaller in size.
Load time
Besides, static linking takes constant load time while dynamic linking takes less load time.
Hence, this is another difference between static linking and dynamic linking.
Compatibility
Furthermore, there will be no compatibility issues with static linking. On the other hand, there
will be compatibility issues with dynamic linking.
Plugins and rule of thumb for using DLLs

Describe the concept of Multithreading in Java.


In Java, Multithreading refers to a process of executing two or more threads simultaneously
for maximum utilization of the CPU. A thread in Java is a lightweight process requiring
fewer resources to create and share the process resources.
Multithreading and Multiprocessing are used for multitasking in Java, but we prefer
multithreading over multiprocessing. This is because the threads use a shared memory area
which helps to save memory, and also, the content-switching between the threads is a bit
faster than the process.
Few more advantages of Multithreading are:

 Multithreading saves time as you can perform multiple operations together.


 The threads are independent, so it does not block the user to perform multiple
operations at the same time and also, if an exception occurs in a single thread, it
does not affect other threads.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 30


MC4204_Mobile Application Development Unit-3
Describe the Life Cycle of a Thread
There are five states a thread has to go through in its life cycle. This life cycle is controlled
by JVM (Java Virtual Machine). These states are:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1. New

In this state, a new thread begins its life cycle. This is also called a born thread. The thread
is in the new state if you create an instance of Thread class but before the invocation of
the start() method.
2. Runnable
A thread becomes runnable after a newly born thread is started. In this state, a thread would
be executing its task.
3. Running
When the thread scheduler selects the thread then, that thread would be in a running state.
4. Non-Runnable (Blocked)
The thread is still alive in this state, but currently, it is not eligible to run.
5. Terminated
A thread is terminated due to the following reasons:
 Either its run() method exists normally, i.e., the thread‘s code has executed the
program.
 Or due to some unusual errors like segmentation fault or an unhandled exception.
A thread that is in a terminated state does not consume ant cycle of the CPU.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 31


MC4204_Mobile Application Development Unit-3
Java Thread Class
The Java Thread class provides methods and constructors to create and perform operations
on a thread. The Java thread class extends the Object class and implements the Runnable
interface.
Java Thread Methods
These are the methods that are available in the Thread class:
1. public void start()
It starts the execution of the thread and then calls the run() on this Thread object.
Example:
1 {
2 public void run()
3 {
4 System.out.println("Thread is running...");
5 }
6 public static void main(String args[])
7 {
8 StartExp1 thread1=new StartExp1();
9 thread1.start();
10 }
11 }
Output:
Thread is running…
2. public void run()
This thread is used to do an action for a thread. The run() method is instantiated if the thread
was constructed using a separate Runnable object.
Example:
1 public class RunExp1 implements Runnable
2 {
3 public void run()
4 {
5 System.out.println("Thread is running...");
6 }
7 public static void main(String args[])
8 {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 32


MC4204_Mobile Application Development Unit-3
9 RunExp1 r1=new RunExp1();
10 Thread thread1 =new Thread(r1);
11 thread1.start();
12 }
13 }
Output:
Thread is running…
3. public static void sleep()
This blocks the currently running thread for the specified amount of time.
Example:
1 public class SleepExp1 extends Thread
2 {
3 public void run()
4 {
5 for(int i=1;i<5;i++)
6 {
7 try
8 {
9 Thread.sleep(500);
10 }catch(InterruptedException e){System.out.println(e);}
11 System.out.println(i);
12 }
13 }
14 public static void main(String args[])
15 {
16 SleepExp1 thread1=new SleepExp1();
17 SleepExp1 thread2=new SleepExp1();
18 thread1.start();
19 thread2.start();
20 }
21 }
Output:
11223344

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 33


MC4204_Mobile Application Development Unit-3
4. public static Thread currentThread()
It returns a reference to the currently running thread.
Example:
1 public class CurrentThreadExp extends Thread
2 {
3 public void run()
4 {
5 System.out.println(Thread.currentThread().getName());
6 }
7 public static void main(String args[])
8 {
9 CurrentThreadExp thread1=new CurrentThreadExp();
10 CurrentThreadExp thread2=new CurrentThreadExp();
11 thread1.start();
12 thread2.start();
13 }
14 }
Output:
Thread-0
Thread-1
5. public void join()
It causes the current thread to block until the second thread terminates or the specified
amount of milliseconds passes.
Example:
1 public class JoinExample1 extends Thread
2 {
3 public void run()
4 {
5 for(int i=1; i<=4; i++)
6 {
7 try
8 {
9 Thread.sleep(500);
10 }catch(Exception e){System.out.println(e);}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 34


MC4204_Mobile Application Development Unit-3
11 System.out.println(i);
12 }
13 }
14 public static void main(String args[])
15 {
16 JoinExample1 thread1 = new JoinExample1();
17 JoinExample1 thread2 = new JoinExample1();
18 JoinExample1 thread3 = new JoinExample1();
19 thread1.start();
20 try
21 {
22 thread1.join();
23 }catch(Exception e){System.out.println(e);}
24 thread2.start();
25 thread3.start();
26 }
27 }
Output:
123411223344
6. public final int getPriority()
It is used to check the priority of the thread. When a thread is created, some priority is
assigned to it. This priority is assigned either by the JVM or by the programmer explicitly
while creating the thread.
Example:
1 public class JavaGetPriorityExp extends Thread
2 {
3 public void run()
4 {
5 System.out.println("running thread name is:"+Thread.currentThread().getName());
6 }
7 public static void main(String args[])
8 {
9 JavaGetPriorityExp t1 = new JavaGetPriorityExp();
10 JavaGetPriorityExp t2 = new JavaGetPriorityExp();

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 35


MC4204_Mobile Application Development Unit-3
11 System.out.println("t1 thread priority : " + t1.getPriority());
12 System.out.println("t2 thread priority : " + t2.getPriority());
13 t1.start();
14 t2.start();
15 }
16 }
Output:
t1 thread priority : 5
t2 thread priority : 5
running thread name is:Thread-0
running thread name is:Thread-1
7. public final void setPriority()
This method is used to change the priority of the thread. The priority of every thread is
represented by the integer number from 1 to 10. The default priority of a thread is 5.
Example:
1 public class JavaSetPriorityExp1 extends Thread
2 {
3 public void run()
4 {
5 System.out.println("Priority of thread is: "+Thread.currentThread().getPriority());
6 }
7 public static void main(String args[])
8 {
9 JavaSetPriorityExp1 t1=new JavaSetPriorityExp1();
10 t1.setPriority(Thread.MAX_PRIORITY);
11 t1.start();
12 }
13 }
Output:
Priority of thread is: 10
8. public final String getName()
This method of thread class is used to return the name of the thread. We cannot override this
method in our program, as this method is final.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 36


MC4204_Mobile Application Development Unit-3
Example:
1 public class GetNameExample extends Thread
2 {
3 public void run()
4 {
5 System.out.println("Thread is running...");
6 }
7 public static void main(String args[])
8 {
9 // creating two threads
10 GetNameExample thread1=new GetNameExample();
11 GetNameExample thread2=new GetNameExample();
12 System.out.println("Name of thread1: "+ thread1.getName());
13 System.out.println("Name of thread2: "+thread2.getName());
14 thread1.start();
15 thread2.start();
16 }
17 }
Output:
Name of thread1: Thread-0
Name of thread2: Thread-1
Thread is running…
Thread is running…
9. public final void setName()
This method changes the name of the thread.
Example:
1 public class SetNameExample extends Thread
2 {
3 public void run()
4 {
5 System.out.println("running...");
6 }
7 public static void main(String args[])
8 {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 37


MC4204_Mobile Application Development Unit-3
9 SetNameExample thread1=new SetNameExample();
10 SetNameExample thread2=new SetNameExample();
11 thread1.start();
12 thread2.start();
13 thread1.setName("Kadamb Sachdeva");
14 thread2.setName("Great learning");
15 System.out.println("After changing name of thread1: "+thread1.getName());
16 System.out.println("After changing name of thread2: "+thread2.getName());
17 }
18 }
Output:
After changing name of thread1: Kadamb Sachdeva
After changing name of thread2: Great Learning
running…
running…
10. public long getId()
It returns the identifier of the thread. The thread ID is a number generated when the thread
was created. This ID cannot be changed during its lifetime. But when the thread is
terminated, the ID can be reused.
Example:
1 public class GetIdExample extends Thread
2 {
3 public void run()
4 {
5 System.out.println("running...");
6 }
7 public static void main(String args[])
8 {
9 GetIdExample thread1=new GetIdExample();
10 System.out.println("Name of thread1: "+thread1.getName());
11 System.out.println("Id of thread1: "+thread1.getId());
12 thread1.start();
13 }
14 }

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 38


MC4204_Mobile Application Development Unit-3
Output:
Name of thread1: Thread-0
Id of thread1: 21
running…
11. public final boolean isAlive()
This method checks if the thread is alive. A thread is in the alive state if the start() method of
thread class has been called and the thread has not yet died.
Example:
1 public class JavaIsAliveExp extends Thread
2 {
3 public void run()
4 {
5 try
6 {
7 Thread.sleep(300);
8 System.out.println("is run() method isAlive "+Thread.currentThread().isAlive());
9 }
10 catch (InterruptedException ie) {
11 }
12 }
13 public static void main(String[] args)
14 {
15 JavaIsAliveExp thread1 = new JavaIsAliveExp();
16 System.out.println("before starting thread isAlive: "+thread1.isAlive());
17 thread1.start();
18 System.out.println("after starting thread isAlive: "+thread1.isAlive());
19 }
20 }
Output:
before starting thread isAlive: false
after starting thread isAlive: true
is run() method isAlive true
12. public static void yield()
This method pauses the execution of the current thread to execute other threads temporarily.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 39


MC4204_Mobile Application Development Unit-3
Example:
1 public class JavaYieldExp extends Thread
2 {
3 public void run()
4 {
5 for (int i=0; i<3 ; i++)
6 System.out.println(Thread.currentThread().getName() + " in control");
7 }
8 public static void main(String[]args)
9 {
10 JavaYieldExp thread1 = new JavaYieldExp();
11 JavaYieldExp thread2 = new JavaYieldExp();
12 thread1.start();
13 thread2.start();
14 for (int i=0; i<3; i++)
15 {
16 thread1.yield();
17 System.out.println(Thread.currentThread().getName() + " in control");
18 }
19 }
20 }
Output:
main in control
main in control
main in control
Thread-0 in control
Thread-0 in control
Thread-0 in control
Thread-1 in control
Thread-1 in control
Thread-1 in control
13. public final void suspend()
This method is used to suspend the currently running thread temporarily. Using the resume()
method, you can resume the suspended thread.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 40


MC4204_Mobile Application Development Unit-3
Example:
1 public class JavaSuspendExp extends Thread
2 {
3 public void run()
4 {
5 for(int i=1; i<5; i++)
6 {
7 try
8 {
9 sleep(500);
10 System.out.println(Thread.currentThread().getName());
11 }catch(InterruptedException e){System.out.println(e);}
12 System.out.println(i);
13 }
14 }
15 public static void main(String args[])
16 {
17 JavaSuspendExp thread1=new JavaSuspendExp ();
18 JavaSuspendExp thread2=new JavaSuspendExp ();
19 JavaSuspendExp thread3=new JavaSuspendExp ();
20 thread1.start();
21 thread2.start();
22 thread2.suspend();
23 thread3.start();
24 }
25 }
Output:
Thread-0
1
Thread-2
1
Thread-0
2
Thread-2

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 41


MC4204_Mobile Application Development Unit-3
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4
14. public final void resume()
This method is used to resume the suspended thread. It is only used with the suspend()
method.
Example:
1 public class JavaResumeExp extends Thread
2 {
3 public void run()
4 {
5 for(int i=1; i<5; i++)
6 {
7 try
8 {
9 sleep(500);
10 System.out.println(Thread.currentThread().getName());
11 }catch(InterruptedException e){System.out.println(e);}
12 System.out.println(i);
13 }
14 }
15 public static void main(String args[])
16 {
17 JavaResumeExp thread1=new JavaResumeExp ();
18 JavaResumeExp thread2=new JavaResumeExp ();
19 JavaResumeExp thread3=new JavaResumeExp ();
20 thread1.start();
21 thread2.start();

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 42


MC4204_Mobile Application Development Unit-3
22 thread2.suspend();
23 thread3.start();
24 thread2.resume();
25 }
26 }
Output:
Thread-0
1
Thread-2
1
Thread-1
1
Thread-0
2
Thread-2
2
Thread-1
2
Thread-0
3
Thread-2
3
Thread-1
3
Thread-0
4
Thread-2
4
Thread-1
4
15. public final void stop()
As the name suggests, this method is used to stop the currently running thread. Remember,
once the thread execution is stopped, it cannot be restarted.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 43


MC4204_Mobile Application Development Unit-3
Example:
1 public class JavaStopExp extends Thread
2 {
3 public void run()
4 {
5 for(int i=1; i<5; i++)
6 {
7 try
8 {
9 sleep(500);
10 System.out.println(Thread.currentThread().getName());
11 }catch(InterruptedException e){System.out.println(e);}
12 System.out.println(i);
13 }
14 }
15 public static void main(String args[])
16 {
17 JavaStopExp thread1=new JavaStopExp ();
18 JavaStopExp thread2=new JavaStopExp ();
19 JavaStopExp thread3=new JavaStopExp ();
20 thread1.start();
21 thread2.start();
22 thread3.stop();
23 System.out.println("Thread thread3 is stopped");
24 }
25 }
Output:
16. public void destroy()
This thread method destroys the thread group as well as its subgroups.
Example:
1 public class JavaDestroyExp extends Thread
2 {
3 JavaDestroyExp(String threadname, ThreadGroup tg)
4 {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 44


MC4204_Mobile Application Development Unit-3
5 super(tg, threadname);
6 start();
7 }
8 public void run()
9 {
10 for (int i = 0; i < 2; i++)
11 {
12 try
13 {
14 Thread.sleep(10);
15 }
16 catch (InterruptedException ex) {
17 System.out.println("Exception encounterted");}
18 }
19 System.out.println(Thread.currentThread().getName() +
20 " finished executing");
21 }
22 public static void main(String arg[]) throws InterruptedException, SecurityException
23 {
24 ThreadGroup g1 = new ThreadGroup("Parent thread");
25 ThreadGroup g2 = new ThreadGroup(g1, "child thread");
26 JavaDestroyExp thread1 = new JavaDestroyExp("Thread-1", g1);
27 JavaDestroyExp thread2 = new JavaDestroyExp("Thread-2", g1);
28 thread1.join();
29 thread2.join();
30 g2.destroy();
31 System.out.println(g2.getName() + " destroyed");
32 g1.destroy();
33 System.out.println(g1.getName() + " destroyed");
34 }
35 }
Output:
Thread-1 finished executing
Thread-2 finished executing

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 45


MC4204_Mobile Application Development Unit-3
child thread destroyed
Parent thread destroyed
17. public final boolean isDaemon()
This thread method will check if the thread is a daemon thread or not. If it is a daemon
thread, then it will return true else, it will return false.
For those who don‘t know about a daemon thread, a daemon thread is a thread that will not
stop the Java Virtual Machine (JVM) from exiting when the program is ended, but the thread
is still running.
Example:
1 public class JavaIsDaemonExp extends Thread
2 {
3 public void run()
4 {
5 //checking for daemon thread
6 if(Thread.currentThread().isDaemon())
7 {
8 System.out.println("daemon thread work");
9 }
10 else
11 {
12 System.out.println("user thread work");
13 }
14 }
15 public static void main(String[] args)
16 {
17 JavaIsDaemonExp thread1=new JavaIsDaemonExp();
18 JavaIsDaemonExp thread2=new JavaIsDaemonExp();
19 JavaIsDaemonExp thread3=new JavaIsDaemonExp();
20 thread1.setDaemon(true);
21 thread1.start();
22 thread2.start();
23 thread3.start();
24 }
25 }

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 46


MC4204_Mobile Application Development Unit-3
Output:
daemon thread work
user thread work
user thread work
18. public final void setDaemon(boolean on)
This method of a thread is used to identify or mark the thread either daemon or a user thread.
The JVM automatically terminates this thread when all the user threads die.
This thread method must run before the start of the execution of the thread.
Example:
1 public class JavaSetDaemonExp1 extends Thread
2 {
3 public void run()
4 {
5 if(Thread.currentThread().isDaemon())
6 {
7 System.out.println("daemon thread work");
8 }
9 else
10 {
11 System.out.println("user thread work");
12 }
13 }
14 public static void main(String[] args)
15 {
16 JavaSetDaemonExp1 thread1=new JavaSetDaemonExp1();
17 JavaSetDaemonExp1 thread2=new JavaSetDaemonExp1();
18 JavaSetDaemonExp1 thread3=new JavaSetDaemonExp1();
19 thread1.setDaemon(true);
20 thread1.start();
21 thread2.setDaemon(true);
22 thread2.start();
23 thread3.start();
24 }
25 }

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 47


MC4204_Mobile Application Development Unit-3
Output:
daemon thread work
daemon thread work
user thread work
19. public void interrupt()
This method of a thread is used to interrupt the currently executing thread. This method can
only be called when the thread is in sleeping or waiting state.
But if the thread is not in the sleeping or waiting state, then the interrupt() method will not
interrupt the thread but will set the interrupt flag to true.
Example:
1 public class JavaInterruptExp1 extends Thread
2 {
3 public void run()
4 {
5 try
6 {
7 Thread.sleep(1000);
8 System.out.println("javatpoint");
9 }catch(InterruptedException e){
10 throw new RuntimeException("Thread interrupted..."+e);
11
12 }
13 }
14 public static void main(String args[])
15 {
16 JavaInterruptExp1 thread1=new JavaInterruptExp1();
17 thread1.start();
18 try
19 {
20 thread1.interrupt();
21 }catch(Exception e){System.out.println("Exception handled "+e);}
22 }
23 }

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 48


MC4204_Mobile Application Development Unit-3
Output:
Exception in thread “Thread-0” java.lang.RuntimeException: Thread
interrupted…java.lang.InterruptedException: sleep interrupted at
JavaInterruptExp1.run(JavaInterruptExp1.java:10)
20. public boolean isInterrupted()
This thread method is used to test whether the thread is interrupted or not. It will return the
value of the internal flag as true or false, i.e. if the thread is interrupted, it will return true
else, it will return false.
Example:
1 public class JavaIsInterruptedExp extends Thread
2 {
3 public void run()
4 {
5 for(int i=1;i<=3;i++)
6 {
7 System.out.println("doing task....: "+i);
8 }
9 }
10 public static void main(String args[])throws InterruptedException
11 {
12 JavaIsInterruptedExp thread1=new JavaIsInterruptedExp();
13 JavaIsInterruptedExp thread2=new JavaIsInterruptedExp();
14 thread1.start();
15 thread2.start();
16 System.out.println("is thread interrupted..: "+thread1.isInterrupted());
17 System.out.println("is thread interrupted..: "+thread2.isInterrupted());
18 thread1.interrupt();
19 System.out.println("is thread interrupted..: " +thread1.isInterrupted());
20 System.out.println("is thread interrupted..: "+thread2.isInterrupted());
21 }
22 }
Output:
is thread interrupted..: false
is thread interrupted..: false

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 49


MC4204_Mobile Application Development Unit-3
is thread interrupted..: true
is thread interrupted..: false
doing task….: 1
doing task….: 2
doing task….: 3
doing task….: 1
doing task….: 2
doing task….: 3
21. public static boolean interrupted()
This thread method is used to check if the current thread is interrupted or not. If this
threading method is to be called twice in succession, then the second call will return as false.
If the interrupt status of the thread is true, then this thread method will set it to false.
Example:
1 public class JavaInterruptedExp extends Thread
2 {
3 public void run()
4 {
5 for(int i=1;i<=3;i++)
6 {
7 System.out.println("doing task....: "+i);
8 }
9 }
10 public static void main(String args[])throws InterruptedException
11 {
12 JavaInterruptedExp thread1=new JavaInterruptedExp();
13 JavaInterruptedExp thread2=new JavaInterruptedExp();
14 thread1.start();
15 thread2.start();
16 System.out.println("is thread thread1 interrupted..:"+thread1.interrupted());
17 thread1.interrupt();
18 System.out.println("is thread thread1 interrupted..:"+thread1.interrupted());
19 System.out.println("is thread thread2 interrupted..:"+thread2.interrupted());
20 }
21 }

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 50


MC4204_Mobile Application Development Unit-3
Output:
is thread thread1 interrupted..: false
is thread thread1 interrupted..: false
is thread thread2 interrupted..: false
doing task….: 1
doing task….: 2
doing task….: 3
doing task….: 1
doing task….: 2
doing task….: 3
22. public static int activeCount()
This method of the thread is used to return the no. of active threads in the currently
executing thread‘s thread group.
The number returned by this threading method is only an estimate number as the number of
threads dynamically changes while this method traverses internal data structures.
Example:
1 public class JavaActiveCountExp extends Thread
2 {
3 JavaActiveCountExp(String threadname, ThreadGroup tg)
4 {
5 super(tg, threadname);
6 start();
7 }
8 public void run()
9 {
10 System.out.println("running thread name is:"
11 +Thread.currentThread().getName());
12 }
13 public static void main(String arg[])
14 {
15 ThreadGroup g1 = new ThreadGroup("parent thread group");
16 JavaActiveCountExp thread1 = new JavaActiveCountExp("Thread-1", g1);
17 JavaActiveCountExp thread2 = new JavaActiveCountExp("Thread-2", g1);
18 System.out.println("number of active thread: "+ g1.activeCount());

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 51


MC4204_Mobile Application Development Unit-3
19 }
20 }
Output:
number of active thread: 2
running thread name is: Thread-1
running thread name is: Thread-2
23. public final void checkAccess()
This thread method identifies if the current thread has permission to modify the thread.
Example:
1 public class JavaCheckAccessExp extends Thread
2 {
3 public void run()
4 {
5 System.out.println(Thread.currentThread().getName()+" finished executing");
6 }
7 public static void main(String arg[]) throws InterruptedException, SecurityException
8 {
9 JavaCheckAccessExp thread1 = new JavaCheckAccessExp();
10 JavaCheckAccessExp thread2 = new JavaCheckAccessExp();
11 thread1.start();
12 thread2.start();
13 thread1.checkAccess();
14 System.out.println(t1.getName() + " has access");
15 thread2.checkAccess();
16 System.out.println(t2.getName() + " has access");
17 }
18 }
Output:
Thread-0 has access
Thread-1 has access
Thread-0 finished executing
Thread-1 finished executing
24. public static boolean holdsLock(Object obj)

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 52


MC4204_Mobile Application Development Unit-3
This thread method checks if the currently executing thread holds the monitor lock on the
specified object. If it does, then this threading method will return true.
Example:
1 public class JavaHoldLockExp implements Runnable
2 {
3 public void run()
4 {
5 System.out.println("Currently executing thread is: " + Thread.currentThread().getName());
6 System.out.println("Does thread holds lock? " + Thread.holdsLock(this));
7 synchronized (this)
8 {
9 System.out.println("Does thread holds lock? " + Thread.holdsLock(this));
10 }
11 }
12 public static void main(String[] args)
13 {
14 JavaHoldLockExp g1 = new JavaHoldLockExp();
15 Thread thread1 = new Thread(g1);
16 thread1.start();
17 }
18 }
Output:
Currently executing thread is: Thread-0
Does thread holds lock? false
Does thread holds lock? true
There are various thread methods that are used for different tasks and purposes. Those thread
methods are as follows:
 public static void dumpStack()
 public StackTraceElement[] getStackTrace()
 public static int enumerate(Thread[] tarray)
 public Thread.State getState()
 public final ThreadGroup getThreadGroup()
 public String toString()
 public final void notify()

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 53


MC4204_Mobile Application Development Unit-3
 public final void notifyAll()
 public void setContextClassLoader(ClassLoader cl)
 public ClassLoader getContextClassLoader()
 public static Thread.UncaughtExceptionHandler
getDefaultUncaughtExceptionHandler()
 public static void
setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)
Thread Creation
While multithreading in Java, you can create a thread using two ways:
1. By extending Thread class
2. By implementing the Runnable interface
What is Thread Class?
Thread class provides the methods and constructors to create and perform operations on a
thread. Thread class extends Object class and implements the Runnable interface.
Various constructors are used in a Thread class, but the commonly used constructors are:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Also, as discussed earlier, there are various thread methods that are used for different
purposes and tasks.
So, these constructors and methods are provided by the Thread class to perform various
operations on a thread.
What is a Runnable Interface?
Runnable Interface is implemented whose instances are intended to be executed by a thread.
It has only one method run().
public void run() – This is used to perform an action for a thread.
Starting a Thread
While multithreading in Java, to start a newly created thread, the start() method is used.
 A new thread starts(with a new callstack).
 The thread moves from the New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 54


MC4204_Mobile Application Development Unit-3

Java Thread Example by extending Thread Class


1 class Multi extends Thread{
2 public void run(){
3 System.out.println("thread is running...");
4 }
5 public static void main(String args[]){
6 Multi thread1=new Multi();
7 thread1.start();
8 }
9 }
Output:
thread is running…
Java Thread Example by implementing Runnable interface
1 class Multi3 implements Runnable{
2 public void run(){
3 System.out.println("thread is running...");
4 }
5
6 public static void main(String args[]){
7 Multi3 m1=new Multi3();
8 Thread thread1 =new Thread(m1);
9 thread1.start();
10 }
11 }
Output:
thread is running…
So, this was the basic understanding of Multithreading in Java. This brings us to an end of
this blog. Hope this helped you understand Multithreading in Java better and gain more
insights into it.
Concurrency and Resource Management

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 55


MC4204_Mobile Application Development Unit-3

Describe the concept of Concurrency and Management in detail


Concurrency is the concept of executing two or more tasks at the same time (in parallel). Tasks
may include methods (functions), parts of a program, or even other programs. With current
computer architectures, support for multiple cores and multiple processors in a single CPU is
very common.
The Java Platform has always offered support for concurrent programming, which was the basis
for implementing many of the services offered by Java EE containers. At Java SE 5, additional
high-level API support for concurrency was provided by the java.util.concurrent package.
Threads and Processes
The two main concurrency concepts are processes and threads.
Processes are primarily associated with applications running on the operating system (OS). A
process has specific runtime resources to interact with the underlying OS and allocate other
resources, such as its own memory, just as the JVM process does. A JVM is in fact a process.
The Java programming language and platform are primarily concerned with threads.
Threads share some features with processes, since both consume resources from the OS or the
execution environment. But threads are easier to create and consume many fewer resources than
a process.
Although concurrent programming solves many problems and can improve performance for
most applications, there are a number of situations where multiple execution lines (threads or
processes) can cause major problems. These situations include the following:
 Deadlocks
 Thread starvation
 Concurrent accessing of shared resources
 Situations when the program generates incorrect data
Main Components of the Concurrency Utilities
The primary components of the concurrency utilities are as follows.
 ManagedExecutorService: A managed executor service is used by applications to execute
submitted tasks asynchronously. Tasks are executed on threads that are started and managed by
the container. The context of the container is propagated to the thread executing the task.
For example, by using an ManagedExecutorService.submit() call, a task, such as the
GenerateReportTask, could be submitted to execute at a later time and then, by using
the Future object callback, retrieve the result when it becomes available.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 56


MC4204_Mobile Application Development Unit-3
 ManagedScheduledExecutorService: A managed scheduled executor service is used by
applications to execute submitted tasks asynchronously at specific times. Tasks are executed on
threads that are started and managed by the container. The context of the container is propagated
to the thread executing the task. The API provides the scheduling functionality that allows users
to set a specific date/time for the Task execution programmatically in the application.
 ContextService: A context service is used to create dynamic proxy objects that capture the
context of a container and enable applications to run within that context at a later time or be
submitted to a Managed Executor Service. The context of the container is propagated to the
thread executing the task.
 ManagedThreadFactory: A managed thread factory is used by applications to create managed
threads. The threads are started and managed by the container. The context of the container is
propagated to the thread executing the task. This object can also be used to provide custom
factories for specific use cases (with custom Threads) and, for example, set specific/proprietary
properties to these objects.
Concurrency and Transactions
The most basic operations for transactions are commit and rollback, but, in a distributed
environment with concurrent processing, it can be difficult to guarantee that commit or rollback
operations will be successfully processed, and the transaction can be spread among different
threads, CPU cores, physical machines, and networks.
Ensuring that a rollback operation will successfully execute in such a scenario is crucial.
Concurrency Utilities relies on the Java Transaction API (JTA) to implement and support
transactions on its components through javax.transaction.UserTransaction, allowing application
developers to explicitly manage transaction boundaries. More information is available in the
JTA specification.
Optionally, context objects can begin, commit, or roll back transactions, but these objects
cannot enlist in parent component transactions.
The following code snippet illustrates a Runnable task that obtains a UserTransaction
and then starts and commits a transaction while interacting with other transactional components,
such as an enterprise bean and a database:

public class MyTransactionalTask implements Runnable {


UserTransaction ut = ... // obtained through JNDI or injection
public void run() {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 57


MC4204_Mobile Application Development Unit-3

// Start a transaction
ut.begin();
// Invoke a Service or an EJB
myEJB.businessMethod();
// Update a database entity using an XA JDBC driver
myEJB.updateCustomer(customer);
// Commit the transaction
ut.commit();
}}
Concurrency and Security
Concurrency Utilities for Java EE defers most security decisions to the application server
implementation. If, however, the container supports a security context, that context can be
propagated to the thread of execution. The ContextService can support several runtime
behaviors, and the security attribute, if enabled, will propagate the container security principal.
Resource management in Java
Explain in detail about the concept of Resource management in java
A resource is an object which is required to be closed once our program finishes. For example, a
file is read, database connection and so on.
Resource management or try-with-resources is a new exception handling mechanism that was
introduced in Java 7, which automatically closes the resources used within the try-catch block.
Usage
To use the try-with-resources statement, you simply need to declare the required resources
within the parenthesis, and the created resource will be closed automatically at the end of the
block. Following is the syntax of the try-with-resources statement.

Syntax
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 58


MC4204_Mobile Application Development Unit-3

Following is the program that reads the data in a file using the try-with-resources statement.
Example
import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {


public static void main(String args[]) {
try(FileReader fr = new FileReader("E://file.txt")) {
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace(); } }}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 59


MC4204-Mobile Application Development Unit-4

Mobile OS: Android, iOS – Android Application Architecture – Understanding the anatomy
of a mobile application - Android basic components –Intents and Services – Storing and
Retrieving data – Packaging and Deployment – Security and Hacking

Mobile OS:
A mobile operating system is an operating system that helps to run other application
software on mobile devices. It is the same kind of software as the famous computer operating
systems like Linux and Windows, but now they are light and simple to some extent.
The operating systems found on smartphones include Symbian OS, iPhone OS, RIM's
BlackBerry, Windows Mobile, Palm WebOS, Android, and Maemo. Android, WebOS, and
Maemo are all derived from Linux. The iPhone OS originated from BSD and NeXTSTEP,
which are related to Unix.
It combines the beauty of computer and hand use devices. It typically contains a cellular
built-in modem and SIM tray for telephony and internet connections. If you buy a mobile, the
manufacturer company chooses the OS for that specific device.
Popular platforms of the Mobile OS
Android OS: The Android operating system is the most popular operating system today.
It is a mobile OS based on the Linux Kernel and open-source software. The android operating
system was developed by Google. The first Android device was launched in 2008.
Bada (Samsung Electronics): Bada is a Samsung mobile operating system that was
launched in 2010. The Samsung wave was the first mobile to use the bada operating system. The
bada operating system offers many mobile features, such as 3-D graphics, application
installation, and multipoint-touch.
BlackBerry OS: The BlackBerry operating system is a mobile operating system
developed by Research In Motion (RIM). This operating system was designed specifically for
BlackBerry handheld devices. This operating system is beneficial for the corporate users
because it provides synchronization with Microsoft Exchange, Novell GroupWise email, Lotus
Domino, and other business software when used with the BlackBerry Enterprise Server.
iPhone OS / iOS: The iOS was developed by the Apple inc for the use on its device. The
iOS operating system is the most popular operating system today. It is a very secure operating
system. The iOS operating system is not available for any other mobiles.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 1


MC4204-Mobile Application Development Unit-4

Symbian OS: Symbian operating system is a mobile operating system that provides a
high-level of integration with communication. The Symbian operating system is based on the
java language. It combines middleware of wireless communications and personal information
management (PIM) functionality. The Symbian operating system was developed by Symbian
Ltd in 1998 for the use of mobile phones. Nokia was the first company to release Symbian OS
on its mobile phone at that time.
Windows Mobile OS: The window mobile OS is a mobile operating system that was
developed by Microsoft. It was designed for the pocket PCs and smart mobiles.
Harmony OS: The harmony operating system is the latest mobile operating system that
was developed by Huawei for the use of its devices. It is designed primarily for IoT devices.
Palm OS: The palm operating system is a mobile operating system that was developed
by Palm Ltd for use on personal digital assistants (PADs). It was introduced in 1996. Palm OS
is also known as the Garnet OS.
WebOS (Palm/HP): The WebOS is a mobile operating system that was developed
by Palm. It based on the Linux Kernel. The HP uses this operating system in its mobile and
touchpads.
Android OS
Android is a software package and linux based operating system for mobile devices such
as tablet computers and smartphones.
It is developed by Google and later the OHA (Open Handset Alliance). Java language is
mainly used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the
mobile experience for end users.
There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc
Open Handset Alliance (OHA)
It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI,
Garmin, Teleca, Ebay, Intel etc.
It was established on 5th November, 2007, led by Google. It is committed to advance
open standards, provide services and deploy handsets using the Android Platform.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 2


MC4204-Mobile Application Development Unit-4

Features of Android
After learning what is android, let's see the features of android. The important features of
android are given below:
 It is open-source.
 Anyone can customize the Android Platform.
 There are a lot of mobile applications that can be chosen by the consumer.
 It provides many interesting features like weather details, opening screen, live RSS
(Really Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage
(SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.
Categories of Android applications
There are many android applications in the market. The top categories are:
o Entertainment
o Tools
o Communication
o Productivity
o Personalization
o Music and Audio
o Social
o Media and Video
o Travel and Local etc.
IOS
IOS is a Mobile Operating System that was developed by Apple Inc. for iPhones,
iPads, and other Apple mobile devices. iOS is the second most popular and most used Mobile
Operating System after Android.
The structure of the iOS operating System is Layered based. Its communication doesn’t
occur directly. The layer’s between the Application Layer and the Hardware layer will help for
Communication. The lower level gives basic services on which all applications rely and the
higher-level layers provide graphics and interface-related services. Most of the system
interfaces come with a special package called a framework.
A framework is a directory that holds dynamic shared libraries like .a files, header
files, images, and helper apps that support the library. Each layer has a set of frameworks that
are helpful for developers.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 3


MC4204-Mobile Application Development Unit-4

Architecture of IOS
COREOSLayer
All the IOS technologies are built under the lowest level layer i.e. Core OS layer.
These technologies include:
 Core Bluetooth Framework
 External Accessories Framework
 Accelerate Framework
 Security Services Framework
 Local Authorization Framework etc.
It supports 64 bit which enables the application to run faster.
CORESERVICESLayer
Some important frameworks are present in the CORE SERVICES Layer which helps
the iOS operating system to cure itself ad provide better functionality. It is the 2nd lowest
layer in the Architecture as shown above. Below are some important frameworks present in
this layer:
 AddressBook Framework
The Address Book Framework provides access to the contact details of the user.
 CloudKit Framework
This framework provides a medium for moving data between your app and iCloud.
 CoreData Framework
This is the technology that is used for managing the data model of a Model View
Controller app.
 CoreFoundation Framework
This framework provides data management and service features for iOS
applications.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 4


MC4204-Mobile Application Development Unit-4

 CoreLocation Framework
This framework helps to provide the location and heading information to the
application.
 CoreMotion Framework
All the motion-based data on the device is accessed with the help of the Core
Motion Framework.
 Foundation Framework
Objective C covering too many of the features found in the Core Foundation
framework.
 Health Kit Framework
This framework handles the health-related information of the user.
 Home Kit Framework
This framework is used for talking with and controlling connected devices with the
user’s home.
 SocialFramework
It is simply an interface that will access users’ social media accounts.
 StoreKit Framework
This framework supports for buying of contents and services from inside iOS apps.
MEDIA Layer
With the help of the media layer, we will enable all graphics video, and audio
technology of the system. This is the second layer in the architecture. The different
frameworks of MEDIA layers are:
 ULKit Graphics
This framework provides support for designing images and animating the view
content.
 CoreGraphics Framework
This framework support 2D vector and image-based rendering ad it is a native
drawing engine for iOS.
 Core Animation
This framework helps in optimizing the animation experience of the apps in iOS.
 MediaPlayer Framework
This framework provides support for playing the playlist and enables the user to
use their iTunes library.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 5


MC4204-Mobile Application Development Unit-4

 AVKit
This framework provides various easy-to-use interfaces for video presentation,
recording, and playback of audio and video.
 OpenAL
This framework is an Industry Standard Technology for providing Audio.
 Core Images
This framework provides advanced support for motionless images.
 GL Kit
This framework manages advanced 2D and 3D rendering by hardware-accelerated
interfaces.
COCOA TOUCH
COCOA Touch is also known as the application layer which acts as an interface for the
user to work with the iOS Operating system. It supports touch and motion events and many
more features. The COCOA TOUCH layer provides the following frameworks :
 EvenKit Framework
This framework shows a standard system interface using view controllers for
viewing and changing events.
 GameKitFramework
This framework provides support for users to share their game-related data online
using a Game Center.
 MapKitFramework
This framework gives a scrollable map that one can include in your user interface
of the app.
 PushKitFramework
This framework provides registration support.
FeaturesofiOSoperating System
Let us discuss some features of the iOS operating system
 Highly Securer than other operating systems.
 iOS provides multitasking features like while working in one application we
can switch to another application easily.
 iOS’s user interface includes multiple gestures like swipe, tap, pinch, Reverse
pinch.
 iBooks, iStore, iTunes, Game Center, and Email are user-friendly.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 6


MC4204-Mobile Application Development Unit-4

 It provides Safari as a default Web Browser.


 It has a powerful API and a Camera.
 It has deep hardware and software integration
ApplicationsofIOSOperating System
Here are some applications of the iOS operating system
 iOS Operating System is the Commercial Operating system of Apple Inc. and is
popular for its security.
 iOS operating system comes with pre-installed apps which were developed by
Apple like Mail, Map, TV, Music, Wallet, Health, and Many More.
 Swift Programming language is used for Developing Apps that would run on
IOS Operating System.
 In iOS Operating System we can perform Multitask like Chatting along with
Surfing on the Internet.
AdvantagesofIOSOperating System
The iOS operating system has some advantages over other operating systems available
in the market especially the Android operating system. Here are some of them-
 More secure than other operating systems.
 Excellent UI and fluid responsive
 Suits best for Business and Professionals
 Generate Less Heat as compared to Android.
DisadvantagesofIOSOperatingSystem
Let us have a look at some disadvantages of the iOS operating system
 More Costly.
 Less User Friendly as Compared to Android Operating System.
 Not Flexible as it supports only IOS devices.
 Battery Performance is poor.
Android Architecture
Android architecture or Android software stack is categorized into five parts:
 linux kernel
 native libraries (middleware),
 Android Runtime
 Application Framework
 Applications

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 7


MC4204-Mobile Application Development Unit-4

Let's see the android architecture first.

 Linux kernel
It is the heart of android architecture that exists at the root of android
architecture. Linux kernel is responsible for device drivers, power management, memory
management, device management and resource access.
 Native Libraries
On the top of linux kernel, their are Native libraries such as WebKit, OpenGL,
FreeType, SQLite, Media, C runtime library (libc) etc.
The WebKit library is responsible for browser support, SQLite is for database,
FreeType for font support, Media for playing and recording audio and video formats.
 Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine)
which is responsible to run android application. DVM is like JVM but it is optimized for
mobile devices. It consumes less memory and provides fast performance.
 Android Framework
On the top of Native libraries and android runtime, there is android framework.
Android framework includes Android API's such as UI (User Interface), telephony,

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 8


MC4204-Mobile Application Development Unit-4

resources, locations, Content Providers (data) and package managers. It provides a lot of
classes and interfaces for android application development.
 Applications
On the top of android framework, there are applications. All applications such as
home, contact, settings, games, browsers are using android framework that uses android
runtime and libraries. Android runtime and native libraries are using linuxkernal.
Understanding the anatomy of a mobile application
Developing Android applications for mobile devices with limited resources requires a thorough
understanding of the application lifecycle. Android uses its own terminology for these
application building blocks—terms such as context, activity, and intent. This chapter familiarizes
you with the most important terms, and their related Java class components, used by Android
applications.
Mastering Important Android Terminology
This chapter introduces you to the terminology used in Android application development and
provides you with a more thorough understanding of how Android applications function and
interact with one another. Here are some of the important terms covered in this chapter:
Context: The context is the central command center for an Android application. Most
application-specific functionality can be accessed or referenced through the context. The
Context class (android.content.Context) is a fundamental building block of any Android
application and provides access to application-wide features such as the application’s private
files and device resources as well as system-wide services. The application-wide Context object
is instantiated as an Application object (android.app.Application).
Activity: An Android application is a collection of tasks, each of which is called an
activity. Each activity within an application has a unique task or purpose. The Activity
class (android.app.Activity) is a fundamental building block of any Android application,
and most applications are made up of several activities. Typically, the purpose is to
handle the display of a single screen, but thinking only in terms of “an activity is a
screen” is too simplistic. An Activity class extends the Context class, so it also has all of
the functionality of the Context class.
Fragment: An activity has a unique task or purpose, but it can be further
componentized; each component is called a fragment. Each fragment within an
application has a unique task or purpose within its parent activity. The Fragment class
(android.app.Fragment) is often used to organize activity functionality in such a way as
to allow a more flexible user experience across various screen sizes, orientations, and
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 9
MC4204-Mobile Application Development Unit-4

aspect ratios. A fragment is commonly used to hold the code and screen logic for placing
the same user interface component in multiple screens, which are represented by multiple
Activity classes.
Intent: The Android operating system uses an asynchronous messaging mechanism to
match task requests with the appropriate activity. Each request is packaged as an intent.
You can think of each such request as a message stating an intent to do something. Using
the Intent class (android.content.Intent) is the primary method by which application
components such as activities and services communicate with one another.

Image Service: Tasks that do not require user interaction can be encapsulated in a
service. A service is most useful when the operations are lengthy (offloading time-
consuming processing) or need to be done regularly (such as checking a server for new
mail). Whereas activities run in the foreground and generally have a user interface, the
Service class (android.app.Service) is used to handle background operations related to an
Android application. The Service class extends the Context class.
The Application Context:
The application Context is the central location for all top-level application functionality.
The Context class can be used to manage application-specific configuration details as well as
application-wide operations and data. Use the application Context to access settings and
resources shared across multiple Activity instances.
Retrieving the Application Context
You can retrieve the Context for the current process using the getApplicationContext()
method, found in common classes such as Activity and Service, like this:
Context context = getApplicationContext();
Using the Application Context
After you have retrieved a valid application Context object, it can be used to access
application-wide features and services, including the following:
Image Retrieving application resources such as strings, graphics, and XML files
Image Accessing application preferences
Image Managing private application files and directories
Image Retrieving uncompiled application assets
Image Accessing system services
Image Managing a private application database (SQLite)
Image Working with application permissions
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 10
MC4204-Mobile Application Development Unit-4

Retrieving Application Resources


You can retrieve application resources using the getResources() method of the application
Context. The most straightforward way to retrieve a resource is by using its resource identifier, a
unique number automatically generated within the R.java class. The following example retrieves
aString instance from the application resources by its resource ID:
String greeting = getResources().getString(R.string.hello);
Accessing Application Preferences
You can retrieve shared application preferences using the getSharedPreferences() method of the
application Context. The SharedPreferences class can be used to save simple application data,
such as configuration settings or persistent application state information.
Accessing Application Files and Directories
You can use the application Context to access, create, and manage application files and
directories private to the application as well as those on external storage.

Retrieving Application Assets


You can retrieve application resources using the getAssets() method of the application Context.
This returns an AssetManager (android.content.res.AssetManager) instance that can then be used
to open a specific asset by its name.
Performing Application Tasks with Activities
The Android Activity class (android.app.Activity) is core to any Android application. Much of
the time, you define and implement an Activity class for each screen in your application. For
example, a simple game application might have the following five activities, as shown in below:

A simple game with five activities

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 11


MC4204-Mobile Application Development Unit-4

A startup or splash screen: This activity serves as the primary entry point to the application. It
displays the application name and version information and transitions to the main menu after a
short interval.

A main menu screen: This activity acts as a switch to drive the user to the core activities of the
application. Here, the users must choose what they want to do within the application.

A game play screen: This activity is where the core game play occurs.

A high scores screen: This activity might display game scores or settings.

A Help/About screen: This activity might display the information the user might need to play the
game.

The Life cycle of an Android Activity

Android applications can be multiprocess, and the Android operating system allows multiple
applications to run concurrently, provided memory and processing power are available.
Applications can have background behavior, and applications can be interrupted and paused
when events such as phone calls occur. Only one active application can be visible to the user at a
time—specifically, a single application Activity is in the foreground at any given time.

The Activity stack

Android applications are responsible for managing their state and their memory, resources, and
data. They must pause and resume seamlessly. Understanding the different states within the
Activity lifecycle is the first step in designing and developing robust Android applications.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 12


MC4204-Mobile Application Development Unit-4

Using Activity Callbacks to Manage Application State and Resources


Different important state changes within the Activity lifecycle are punctuated by a series of
important method callbacks.

The life cycle of an Android Activity

Here are the method stubs for the most important callbacks of the Activity class:

public class MyActivity extends Activity {

protected void onCreate(Bundle savedInstanceState);

protected void onStart();

protected void onRestart();

protected void onResume();

protected void onPause();

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 13


MC4204-Mobile Application Development Unit-4

protected void onStop();

protected void onDestroy();

Android Basic Components

An android component is simply a piece of code that has a well defined life cycle e.g.
Activity, Receiver, Service etc.
The core building blocks or fundamental components of android are activities, views,
intents, services, content providers, fragments and AndroidManifest.xml.
Activity
An activity is a class that represents a single screen. It is like a Frame in AWT.
View
A view is the UI element such as button, label, text field etc. Anything that you see is a
view.

Intent
Intent is used to invoke components. It is mainly used to:
o Start the service
o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o Dial a phone call etc.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 14


MC4204-Mobile Application Development Unit-4

For example, you may write the following code to view the webpage.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);
Service
Service is a background process that can run for a long time.
There are two types of services local and remote. Local service is accessed from within
the application whereas remote service is accessed remotely from other applications running on
the same device.
Content Provider
Content Providers are used to share data between the applications.
Fragment
Fragments are like parts of activity. An activity can display one or more fragments on the
screen at the same time.
AndroidManifest.xml
It contains informations about activities, content providers, permissions etc. It is like the
web.xml file in Java EE.
Android Virtual Device (AVD)
It is used to test the android application without the need for mobile or tablet etc. It can
be created in different configurations to emulate different types of real devices.
Storing and Retrieving data
Android also supports data storage in a local database, and the operating system provides a good
infrastructure for storing and retrieving data. In most cases, the most simple and straightforward
way to acquire and preserve user data is via SQLite databases.
Ways to store data
 Shared Preferences
 Internal storage
 External storage
 SQLite databases
Shared Preferences
Shared Preferences is the way to go if you’re saving primitive data as key-value pairs. It requires
a key, which is a String, and the corresponding value for the said key. The value can be any of
the following: a boolean, float, int, long, or another string.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 15


MC4204-Mobile Application Development Unit-4

Your Android device stores each app’s Shared Preferences inside of an XML file in a private
directory.
Before you can store data with shared preferences, you must first get a SharedPreferences
object. There are two Context methods that you can use to retrieve a SharedPreferences
object.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
For when your app will have a single preferences file, and
SharedPreferences sharedPreferences = getSharedPreferences(fileNameString, MODE_PRIVATE);
for when your app could have multiple preferences files, or if you prefer to name your
SharedPreferences instance.
On getting the SharedPreferences object, you then access its Editor using the edit() method.
To actually add a value, use the Editor’s putXXX() method, where XXX is one of Boolean,
String, Float, Long, Int, or StringSet. You can also remove a key-value preference pair with
remove().
Finally, make sure to call the Editor’s commit() method after putting or removing values. If
you don’t call commit, your changes will not be persisted.
For our sample app, we allow the user to specify a SharedPreferences filename. If the user
specifies a name, we request for the SharedPreferences with that name; if not, we request the
default SharedPreference object.
String fileNameString = sharedPreferencesBinding.fileNameEditView.getText().toString();
SharedPreferences sharedPreferences;
if(fileNameString.isEmpty()) {
sharedPreferences = getPreferences(MODE_PRIVATE);
}
else {
sharedPreferences = getSharedPreferences(fileNameString, MODE_PRIVATE);
}
Internal storage
Using internal storage is similar to saving with any other file system. You can get references
to File objects, and you can store data of virtually any type using a FileOutputStream. What
sets it apart is the fact that its contents are only accessible by your app.
To get access to your internal file directory, use the Context getFilesDir() method. To create
(or access) a directory within this internal file directory, use the getDir(directoryName,

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 16


MC4204-Mobile Application Development Unit-4

Context.MODE_XXX) method. The getDir() method returns a reference to a File object


representing the specified directory, creating it first if it doesn’t exist.
File directory;
if (filename.isEmpty()) {
directory = getFilesDir();
}
else {
directory = getDir(filename, MODE_PRIVATE);
}
File[] files = directory.listFiles();
In the sample above, if the user-specified filename is empty, we get the base internal storage
directory. If the user specifies a name, we get the named directory, creating first if needed.
To read files, use your preferred file reading method. For our example, we read the complete
file using a Scanner object. To read a file that’s directly within your internal storage
directory (not in any subdirectory), you can use the openFileInput(fileName) method.
FileInputStream fis = openFileInput(filename);
Scanner scanner = new Scanner(fis);
scanner.useDelimiter("\\Z");
String content = scanner.next();
scanner.close();
Similarly, to access a file for writing directly within the Internal Storage directory, use the
openFileOutput(fileName) method. To save files, we use the FileOutputStream write.
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(internalStorageBinding.saveFileEditText.getText().toString().getBytes());
fos.close();
External Storage
Google has made a few key changes to external storage, beginning with Android 10 and
continuing in Android 11. To give users better control over their files and cut down on clutter,
apps now have scoped access to external storage by default. This means that they can tap into the
specific directory on external storage and the media that the app creates.
Apps are expected to store files in one of two app-specific locations designed for the app’s
specific persistent files and cached files, respectively. To access these locations, the app must
verify the storage is available (which is not guaranteed, as it is for internal storage). The
volume’s state can be queried using:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 17


MC4204-Mobile Application Development Unit-4

Environment.getExternalStorageStage().
If MEDIA_MOUNTED is returned, that means you can read and write files to external
storage. You will find a number of predefined directories that should aid with logical storage
and prevent clutter. These include the likes of DIRECTORY_DOCUMENTS and
DIRECTORY_MOVIES.
SQLite
SQLite is a relational database technology that’s used most often when the developer requires an
embedded database in a small system. SQLite is included with the Android system and can be
easily used in your Android app.
For this sample, we create a single table.
public class SampleSQLiteDBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "sample_database";
public static final String PERSON_TABLE_NAME = "person";
public static final String PERSON_COLUMN_ID = "_id";
public static final String PERSON_COLUMN_NAME = "name";
public static final String PERSON_COLUMN_AGE = "age";
public static final String PERSON_COLUMN_GENDER = "gender";

public SampleSQLiteDBHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + PERSON_TABLE_NAME + " (" +
PERSON_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+
PERSON_COLUMN_NAME + " TEXT, " +
PERSON_COLUMN_AGE + " INT UNSIGNED, " +
PERSON_COLUMN_GENDER + " TEXT" + ")");
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 18
MC4204-Mobile Application Development Unit-4

sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + PERSON_TABLE_NAME);


onCreate(sqLiteDatabase);
}
}
To add data:
private void saveToDB() {
SQLiteDatabase database = new SampleSQLiteDBHelper(this).getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SampleSQLiteDBHelper.PERSON_COLUMN_NAME,
activityBinding.nameEditText.getText().toString());
values.put(SampleSQLiteDBHelper.PERSON_COLUMN_AGE,
activityBinding.ageEditText.getText().toString());
values.put(SampleSQLiteDBHelper.PERSON_COLUMN_GENDER,
activityBinding.genderEditText.getText().toString());
long newRowId = database.insert(SampleSQLiteDBHelper.PERSON_TABLE_NAME,
null, values);

Toast.makeText(this, "The new Row Id is " + newRowId,


Toast.LENGTH_LONG).show();
}
To read data:
private void readFromDB() {
String name = activityBinding.nameEditText.getText().toString();
String gender = activityBinding.genderEditText.getText().toString();
String age = activityBinding.ageEditText.getText().toString();
if(age.isEmpty())
age = "0";
SQLiteDatabase database = new SampleSQLiteDBHelper(this).getReadableDatabase();
String[] projection = {
SampleSQLiteDBHelper.PERSON_COLUMN_ID,
SampleSQLiteDBHelper.PERSON_COLUMN_NAME,
SampleSQLiteDBHelper.PERSON_COLUMN_AGE,
SampleSQLiteDBHelper.PERSON_COLUMN_GENDER
};
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 19
MC4204-Mobile Application Development Unit-4

String selection =
SampleSQLiteDBHelper.PERSON_COLUMN_NAME + " like ? and " +
SampleSQLiteDBHelper.PERSON_COLUMN_AGE + " > ? and " +
SampleSQLiteDBHelper.PERSON_COLUMN_GENDER + " like ?";
String[] selectionArgs = {"%" + name + "%", age, "%" + gender + "%"};
Cursor cursor = database.query(
SampleSQLiteDBHelper.PERSON_TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // don't sort
);
Log.d("TAG", "The total cursor count is " + cursor.getCount());
activityBinding.recycleView.setAdapter(new MyRecyclerViewCursorAdapter(this,
cursor));
}
SQLite storage offers the power and speed of a full-featured relational database to your app.
If you intend to store data that you may later query, you should consider using the SQLite
storage option.
Saving cache files
Android also provides a means to cache some data rather than store it permanently. You can
cache data in either internal storage or external storage. Cache files may be deleted by the
Android system when the device is low on space.
We are able to save or read data from the device internal memory. FileInputStream and
FileOutputStream classes are used to read and write data into the file.
Here, we are going to read and write data to the internal storage of the device.
Example of reading and writing data to the android internal storage
activity_main.xml
Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file
will like this:
File: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 20
MC4204-Mobile Application Development Unit-4

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="20dp"
android:layout_marginTop="24dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="24dp"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="File Name:" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 21
MC4204-Mobile Application Development Unit-4

android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Data:" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginLeft="70dp"
android:layout_marginTop="16dp"
android:text="save" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="read" />
</RelativeLayout>
Activity class
Let’s write the code to write and read data from the internal storage.
File: MainActivity.Java
Package example.javatpoint.com.internalstorage:
importandroid.content.Context;
import android.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importanroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 22
MC4204-Mobile Application Development Unit-4

importjava.io.BufferedReader;
importJava.io.FileNotFoundException;
importjava.io.FileOutputstream;
importjava.io.IOException;
importjava.io.InputStreamReader;
Public class MainActivity extends AppCompatActivity{
EditTexteditTextFileName.editTextData;
Button saveButton,readButton;
@Override
protected void onCreat(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity main);
editTextFileName=findViewById(R.id.editText1);
editTextData=findViewById(R.id.editText2);
saveButton=findViewById(R.id.button1);
readButton=findViewById(R.id.button2);
//Performing Action on Read Button
saveButton.setOnClickListener(new View.OnClickListerner(){
@Override
Public void onClick(View arg0) {
String filename=editTextFileName.getTexxt().toString();
String data=editTextData.getText().toString();
FileOutpustreamfos;
try {
fos=openFileOutput(filename.Context.MODE_PRIVATE);
//default mode is PRIVATE. Can be APPEND etc.
fos.write(data.getBytes());
fos.close();
Toast.makeText(getApplicationContext().filename+"saved",
Toast.LENGTH_LONG).show();

} catch (FileNotFoundException e) {e.PrintStackTrace();}


catch (IOException e) {e.printStackTrace();}
}
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 23
MC4204-Mobile Application Development Unit-4

});
//Performing Action on Read Button
readButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
StringBufferstringBuffer=new StringBuffer();
try{ //Attaching BufferedReader to the FileInputStream by the help of
InputStreamReader
BufferedReaderinputReader=new BufferedReader(new InputStreamReader(
openFileInput(filename)));
String inputString;
//Reading data line by line and storing in into the stringbuffer
While ((inputString=inputReader.readLine())!=null) {
stringBuffer.append(inputString + "\n");
} } catch (IOException e) {
e.printStactTrace(); }
//Displayingdataonthetoast
Toast.makeText(getApplicationContext(),stringBuffer.toString(),Toast.LENGTH_LONG).show
();
} }); }}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 24


MC4204-Mobile Application Development Unit-4

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 25


MC4204-Mobile Application Development Unit-4

Packaging and Deployment


Packaging and deployment are part of a multistep process that retrieves build output, packages
the output, transfers or copies the package to another location, and then deploys it to
corresponding containers and runtime environments in test or production systems.
A package is a namespace that combines a set of relevant classes and interfaces. Conceptually
one can consider packages as being similar to various folders on your computer. One might
have HTML pages in one folder, images in another, and scripts or applications in yet another.
Because in android, software written in the Java/Kotlin programming language can be made
of hundreds or thousands of different classes, it makes sense to keep things organized by
placing related classes and interfaces into packages. A package is basically the directory
(folder) in which the source code resides. Normally, this is a directory structure that uniquely
distinguishes the android application; such as com.example.app. Then the developer can build
packages within the application package that divides the code; such
as com.example.app.ui or com.example.app.data. The package for each android application
resides within the src/main/java directory of the application module. The developer could
put a different package within the application package to separate each “layer” of the
application architecture.
During android app development sometimes the developers need to separate the Java/Kotlin
classes according to their functionality. Having various java classes in different package name
make the project more understandable for anyone. So in this article, we are going to discuss
how could a developer create a new package inside the Src folder in Android Studio.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 26


MC4204-Mobile Application Development Unit-4

Step by Step Implementation

Step 1: To create a new package inside the Src folder in Android studio open your project
in Android mode first as shown in the below image.

Step 2: Now go to the java > right-click > New > Package as shown in the below image.

Step 3: Then a pop-up screen will arise like below and here select the main\java and click
on OK.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 27


MC4204-Mobile Application Development Unit-4

Step 4: On the next screen write down your new package name. Here I have given my new
package name GeeksforGeeks. And you are done.

Now go to the app > java > GeeksforGeeks and you can find your new package as shown in
the below image. You can keep separate Java or Kotlin files inside it.

Deploying Your Signed Android Application


After you successfully configure your development environment for Android application
development, you can deploy your application as a signed package. You can later upload the
signed package to application stores such as Google Play or Amazon.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 28


MC4204-Mobile Application Development Unit-4

Before you generate a signed application package, you must check the settings of your
application, such as the application version, and update any settings that are incorrect. See
Preparing an Android Application for Deployment.
To generate a signed package containing your application, do the following:

On the Project Manager, expand the Build Configurations node and double-click the Release
configuration, or any other platform-agnostic configuration that you want to use to build your
signed application package.
Expand the Target Platforms node and double-click the Android target platform to select that
platform. The selected target platform is displayed using a bold font.
Expand the Android node, expand the Configuration node within, and double-click the
Application Store platform configuration node to select that platform configuration. The selected
platform configuration is displayed using a bold font.
Select Project > Options > Provisioning, and check that all fields are filled with the right values.
A keystore file and a certificate are required to sign your application.
Select Project > Deployment, and click the Deploy DMgrDeploy.png button to deploy your
application.
RAD Studio builds your application using the Android SDK you previously added to the IDE
and signs your application using the signing certificate specified in the Provisioning page.
You can find your signed application package (.apk) in your project folder:
<Your Project Folder>\Android\<Selected Configuration>\<Project Name>\bin\<Project
Name>.apk
For example: C:\Users\Myname\Documents\RAD
Studio\Projects\ProjectFolder\Android\Release\MyProject\bin\MyProject.apk.
Security and Hacking
Android has built-in security features that significantly reduce the frequency and impact of
application security issues. The system is designed so that you can typically build your apps
with the default system and file permissions and avoid difficult decisions about security.
The following core security features help you build secure apps:
App sandbox
The Android platform takes advantage of the Linux user-based protection to identify and isolate
app resources. To do this, Android assigns a unique user ID (UID) to each Android app and runs
it in its own process. Android uses this UID to set up a kernel-level App Sandbox.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 29


MC4204-Mobile Application Development Unit-4

App signing
App signing allows developers to identify the author of the app and to update their app without
creating complicated interfaces and permissions. Every app that runs on the Android platform
must be signed by the developer.
Authentication
Android uses the concept of user-authentication-gated cryptographic keys that requires
cryptographic key storage and service provider and user authenticators.
On devices with a fingerprint sensor, users can enroll one or more fingerprints and use those
fingerprints to unlock the device and perform other tasks. The Gatekeeper subsystem performs
device pattern/password authentication in a Trusted Execution Environment (TEE).
Android 9 and higher includes Protected Confirmation, which gives users a way to formally
confirm critical transactions, such as payments.
Biometrics
Android 9 and higher includes a BiometricPrompt API that app developers can use to integrate
biometric authentication into their apps in a device- and modality-agnostic fashion. Only strong
biometrics can integrate with BiometricPrompt.
Encryption
Once a device is encrypted, all user-created data is automatically encrypted before committing it
to disk and all reads automatically decrypt data before returning it to the calling process.
Encryption ensures that even if an unauthorized party tries to access the data, they won’t be able
to read it.
Keystore
Android offers a hardware-backed Keystore that provides key generation, import and export of
asymmetric keys, import of raw symmetric keys, asymmetric encryption and decryption with
appropriate padding modes, and more.
Security-Enhanced Linux
As part of the Android security model, Android uses Security-Enhanced Linux (SELinux) to
enforce mandatory access control (MAC) over all processes, even processes running with
root/superuser privileges (Linux capabilities).
Trusty Trusted Execution Environment (TEE)
Trusty is a secure Operating System (OS) that provides a Trusted Execution Environment (TEE)
for Android. The Trusty OS runs on the same processor as the Android OS, but Trusty is
isolated from the rest of the system by both hardware and software.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 30


MC4204-Mobile Application Development Unit-4

Verified Boot
Verified Boot strives to ensure all executed code comes from a trusted source (usually device
OEMs), rather than from an attacker or corruption. It establishes a full chain of trust, starting
from a hardware-protected root of trust to the bootloader, to the boot partition and other verified
partitions.
Hacking
Mobile hacking apps break or crack the security measures of a software system by penetrating or
interfering with the security layout. They perform network security assessments too.
Android hacking apps are application packages ready to install in a device, APK, and can
modify HTML responses. Some apps have features to identify the weak links in the security of a
system, control WiFi, lock screen widget, and map devices.
These hacking apps have dozens of free network tools with modifications that make them
undetectable by anti-virus scanners.
Following is a handpicked list of the Top best Android hacking apps and great hacking tools,
with their popular features and download links. The list contains open-source (free) and
commercial(paid) software.
Name Reason Chosen Founded
AndroRAT It is versatile and enables access to Android devices remotely, and is 2012
undetectable by anti-virus scanners
cSploit It is the best hacking app for new hackers because it would allow them to 2017
learn new techniques
DroidSheep It is the most efficient mobile hacking app for use if you want to hack social 2012
media accounts and other messaging apps like Facebook and Instagram
on Android devices.
Kali NetHunter It runs security analysis efficiently and also has multi-language support. 2014
Network Mapper It maps out the security of a system and finds the vulnerabilities on its own 1997
NetX Network Tool Its design makes fetching and accessing information from network 2008
analysis easy
Sniffer Wicap It has a friendly UX, is simple to understand, and does not need root 2013
access.
Hackode Scans target security system and expose vulnerability 2013
zAnti It modifies HTML responses and requests, and access password 2012
WiFiKiLL It is able to disable devices connected to a Wi-Fi network. 2016

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 31


MC4204-Mobile Application Development Unit-4

PART –A

2 MARKS

1. List features of the Android Operating System

2. Write the directory path where images are stored while developing Android
applications.

3. Define services in Android operating system

4. Illustrate the types of Mobile OS

5. What is meant by fragment?

6. Write the merits and demerits of IOS

7. Define OHA and its uses

8. List out some Android basic components

9. What do you understand by security in android application?

10. Define Package and Deployment.

11. List the features of iOS?

12. What is SQLite?

13 AND 15 MARKS

1. Explore the Steps to install and configure Android Studio and SDK

2. Describe the significance of SQLite database in Anroid

3. Describe the Anroid architecture in detail.

4. Discuss different types of mobile OS in detail.

5. Explain in detail about packaging and its applications?

6. Explain the concept of Storing and Retreiving data in mobile application.

7. How to deploy the android application. Explain with example.

8. Discuss in detail about the anatomy of mobile application with neat diagram.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 32


MC4204_Mobile Application Development Unit-5

Communication via the Web – Notification and Alarms – Graphics and Multimedia:
Layer Animation, Event handling and Graphics services – Telephony – Location based
services

5.1 Communication via the Web


Web-based communication is defined as the sharing of information, words or ideas
over a network of computers known as the Internet. Email is an example of web-based
communication. Online webinars are an example of web-based communication.
What are the various ways to communicate using internet. Explain it
10 Ways to Communicate Using the Internet
In the early 1990s, Tim Berners-Lee, a researcher at the European Organization for
Nuclear Research (CERN) developed the hypertext markup language used to build web
pages. Web browsers soon became available for operating systems at the time, including
Microsoft's Windows 95. Chat programs, such as Yahoo Messenger and AOL Instant
Messenger, also became popular in the 1990s. Email became widespread, with people
receiving addresses from their internet service providers or employers and, soon, from free
services such as Yahoo Mail, Microsoft's Hotmail and Google's Gmail.
1. Email
Email is one of the most fundamental internet communication tools. Email addresses
are required to sign up for many services online, and it's generally assumed that everyone on
the internet has at least one email address. Email addresses are available from many free
services, most prominently from big companies like Microsoft and Google. Some internet
service providers also still provide their users with email addresses.
Email has been used as a means for spreading malware as well as for scams known as
phishing, where someone impersonates a trusted sender in order to trick the recipient into
sharing passwords, account numbers or other sensitive data. As a result, it's important to be
cautious when receiving email with unexpected attachments, which could be viruses, or
requests for funds or information, which could be scams. If you're not sure an email is
legitimate, contact the person who allegedly sent it using another means, like the telephone.
2. Internet Relay Chat
Dating back to the 1980s, internet relay chat was one of the earliest chat tools on the
internet. It's still in use today for recreational purposes, coordinating work teams and
handling tech support for some open-source software products.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 1


MC4204_Mobile Application Development Unit-5

Using networks of internet servers and specialized client software, IRC let anyone set up chat
rooms, or "channels," devoted to topics of their choice. It influenced subsequent chat systems
such as AOL and Yahoo chat and even contributed the convention of using the "@" symbol
before a username and the "#" symbol to denote a topic.
3. Instant Messaging Services
In the 1990s, computer-based instant messaging tools such as ICQ, AOL Instant
Messenger, MSN Messenger and Yahoo Messenger became popular ways to stay in touch
with people down the street or around the world for no cost beyond whatever users already
paid to connect to the internet. Some of these tools developed cult followings among
particular types of users, such as Yahoo Messenger's rise among oil traders.
Most of these early tools have since been retired by the companies that operated them, though
a few, such as ICQ, live on with loyal fan bases.
4. Smart Phone Messaging Apps
Most of the 1990s chat tools have since been supplanted by a new breed of messaging
tools, including Facebook Messenger, Google Hangouts, Apple Messages and simple
cellphone-based text messaging. Many of these tools work on smart phones as well as
desktop computers, or even on smart phones alone, and they contain more features than their
earlier counterparts.
Workplace messaging tools, such as Slack and Microsoft Teams, have also become
popular in many companies as a way to share information without picking up the phone or
even drafting an email.
5. Internet Message Boards
Many of today's internet users are familiar with the concept of online discussion
forums, including Facebook groups, subreddits on the forum site Reddit or independent
forums on special interest sites. These let people discuss the news of the day or details of
their hobbies, medical conditions or hometowns. Many have moderators in place to keep the
peace and repel trolls, fraudsters and other undesirable users.
As the old saying goes, don't believe everything you read. This is especially true when
it comes to online message boards, where rumors and misinformation can spread quickly. It's
also a good idea to hold your temper rather than get into fights, or flame wars, on these
forums.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 2


MC4204_Mobile Application Development Unit-5

6. Early Days of Usenet


Before today's forum sites, there was Usenet. Usenet, which still exists in diminished
form, is a set of distributed discussion groups focusing on anything from UFOs to football. In
its heyday, users would connect to a Usenet server, often run by their ISP, and download the
latest messages from the newsgroups they subscribed to using a specialized program called
a newsreader. When they wanted to post messages, they would compose them in their
newsreader, often while offline, then upload them when they next signed online.
Usenet also allowed for the direct distribution of large files, which has at times been used for
piracy. Most modern forum sites limit uploads to small images.
7. The World Wide Web
The World Wide Web may have started as an experimental research project at CERN,
but it's since become one of the dominant media of the world. Pretty much every major
business, organization and government agency has a website, and many individuals do as
well.
Users access the web through specialized programs called web browsers,
including Microsoft Edge, Google Chrome, Mozilla Firefox and Apple Safari, which are
available for computers and other devices such as smart phones, tablets and even video game
systems. Websites are built using languages called HTML, which spells out the basic
structure of a website; CSS, which specifies details of how its elements look on the screen;
and JavaScript, which provides programming logic to process interactivity and process data.
For many people, the web is where they get their news, do their shopping, listen to music,
watch TV and communicate with friends, displacing many media that existed in the
past. Many people have migrated to the web from other media, changing the economics for
TV networks, newspapers, phone companies and others. The web is still relatively young,
and it's likely to continue to evolve in coming decades even as it remains one of the dominant
communication tools in the world.
8. Social Networking Tools
Some of the most popular internet communication tools are social networking
services, including Facebook, Twitter, Facebook-owned Instagram, Snapchat and work-
oriented LinkedIn. These services generally enable people to connect with and follow posts
from a chosen group of associates, sharing updates about their lives, careers or musings
throughout the day.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 3


MC4204_Mobile Application Development Unit-5

People frequently use social networking tools to stay in touch with remote friends and
family and simply for entertainment. Some people follow updates from celebrities on social
media, and the networks have changed how politicians and entertainers communicate with
the public. Many people use them as a way to follow the news as well, following media
organizations on Facebook or even individual journalists on Twitter. Social networking sites
are generally free and supported by advertising.
Social networking tools have run into some controversy over the spread of rumors,
fake news stories, hate speech and other undesirable content, and some network operators
have taken steps to reduce such behavior.
Since the tools are still relatively young, they're likely to continue to evolve in coming years
and decades to continue to meet user needs.
9. Internet Phone Calling
Many people have switched to internet-based calling systems, using what's
called Voice over Internet Protocol (VoIP), from traditional telephones, especially in office
settings. VoIP systems can be cheaper and faster to set up than traditional phones, and they
often allow international and long-distance calling for a fraction of the cost of landline
telephones.
These systems are available through internet service providers, including many cable
and traditional phone providers, as well as through independent providers that can use your
existing internet connection.
10. Video Calls and Conferences
Video calling has also become popular for staying in touch with friends or family and
for work conference calls that, in the past, would have been audio-only. Adding video makes
it possible to see people's facial expressions, which can lead to easier communication.
Coworkers can also share presentations and files through video systems, making sure
everyone is literally on the same page during a discussion. One downside, of course, is that
people need a professional environment and attire for a call that, if audio-only, could be
placed from anywhere and in any kind of dress.
Popular video chat systems include Microsoft's Skype, Google Hangouts and Apple
FaceTime. Video chat facilities are also built into popular office messaging tools such
as Slack. It's generally possible to video chat with any modern computer or smart phone
equipped with a working camera. Many video chat programs enable people to have audio-
only chats if they prefer.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 4


MC4204_Mobile Application Development Unit-5

The Future of Internet Communication


Nobody knows for certain what the future internet will look like, but it's unlikely that
we're done innovating. Companies continue to experiment with new styles of internet-
enabled tools, from virtual reality headsets to smart watches to smart speakers equipped
with virtual assistants. Technologies that used to be separate from the internet, such as
televisions, cellphones and video game consoles, have all gotten networked by default in
recent years.
It's likely that some technologies like email and the basic web will persist, but it's
quite possible that some of the social networking and chat systems will be replaced in the
future, just as the current players replaced earlier such systems.

What is meant by Notifications? Explain its detail with example


5.2 Android Notifications
Android Notification provides short, timely information about the action happened in
the application, even it is not running. The notification displays the icon, title and some
amount of the content text.
Set Android Notification Properties
The properties of Android notification are set using NotificationCompat.Builder object.
Some of the notification properties are mention below:
o setSmallIcon(): It sets the icon of notification.
o setContentTitle(): It is used to set the title of notification.
o setContentText(): It is used to set the text message.
o setAutoCancel(): It sets the cancelable property of notification.
o setPriority(): It sets the priority of notification.
Example
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.androi
d.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 5


MC4204_Mobile Application Development Unit-5

android:layout_height="match_parent"
tools:context="example.javatpoint.com.androidnotification.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDROID NOTIFICATION"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Notify" />
</android.support.constraint.ConstraintLayout>
Create an activity named as activity_notification_view.xml and add the following code. This
activity will be launched on clicking the notification. TextView is used to display the
notification message.
activity_notification_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.androi
d.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.androidnotification.NotificationView">
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="your detail of notification..."
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
<TextView
android:id="@+id/textView"

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 6


MC4204_Mobile Application Development Unit-5

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.096"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintVertical_bias="0.206"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
</android.support.constraint.ConstraintLayout>

MainActivity.java
In the MainActivity.java class adds the following code. In this class, clicking the button
calls the addNotification() method where we implement the NotificationCompat.Builder
object to set the notification properties. The NotificationManager.notify() method is used to
display the notification. The Intent class is used to call another activity
(NotificationView.java) on taping the notification.
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button b1;
@Override

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 7


MC4204_Mobile Application Development Unit-5

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}
private void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.messageicon)
.setContentTitle("Sample")
.setContentText("Hello World")
.setAutoCancel(true) // makes auto cancel of notification
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Intent notificationIntent = new Intent(this, NotificationView.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("message", "This is a notification message");

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,


PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.
NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 8


MC4204_Mobile Application Development Unit-5

NotificationView.java
The NotificationView.java class receives the notification message and is displayed in
TextView. This class is invoked while taping the notification.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class NotificationView extends AppCompatActivity {


TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_view);
textView = findViewById(R.id.textView);
String message=getIntent().getStringExtra("message");
textView.setText(message);
}
}

Output

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 9


MC4204_Mobile Application Development Unit-5

Discuss in detail about Alarm with example program.


5.2 Android Alarm Manager
Android Alarm Manager allows you to access system alarm.
By the help of Android AlarmManager in android, you can schedule your application to
run at a specific time in the future. It works whether your phone is running or not.
The Android AlarmManager holds a CPU wake lock that provides guarantee not to sleep the
phone until broadcast is handled.
Example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.alarmmanager.MainActivity">
<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"/>
</RelativeLayout>
Activity class
The activity class starts the alarm service when user clicks on the button.
MainActivity.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 10


MC4204_Mobile Application Development Unit-5

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
Button start;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start= findViewById(R.id.button);

start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startAlert();
}
});
}
public void startAlert(){
EditText text = findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 11


MC4204_Mobile Application Development Unit-5

Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).sho


w(); } }
create BroadcastReceiver class that starts alarm.
MyBroadcastReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver
{ MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent)
{
mp=MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
} }
Output:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 12


MC4204_Mobile Application Development Unit-5

Illustrate and explain Graphics and Multimedia. Describe its concept with
neat diagram and give example.
5.3 Graphics and Multimedia
Make your images look and perform their best on Android using various APIs for
bitmaps, drawables, and other types of graphics.
A Drawable is a general abstraction for something that can be drawn. The various
subclasses help with specific image scenarios, and you can extend them to define your own
drawable objects that behave in unique ways.
There are two ways to define and instantiate a Drawable besides using the class constructors:
 Inflate an image resource (a bitmap file) saved in your project.
 Inflate an XML resource that defines the drawable properties.
Create drawables from resource images
You can add graphics to your app by referencing an image file from your project resources.
Supported file types are PNG (preferred), JPG (acceptable), and GIF (discouraged). App
icons, logos, and other graphics, such as those used in games, are well suited for this
technique.
To use an image resource, add your file to the res/drawable/ directory of your project. Once
in your project, you can reference the image resource from your code or your XML layout.
Either way, it's referred to using a resource ID, which is the file name without the file type
extension. For example, refer to my_image.png as my_image.
The following code snippet demonstrates how to build an ImageView that uses an image
created from a drawable resource and adds it to the layout:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 13


MC4204_Mobile Application Development Unit-5

ConstraintLayout constraintLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Create a ConstraintLayout in which to add the ImageView


constraintLayout = new ConstraintLayout(this);

// Instantiate an ImageView and define its properties


ImageView i = new ImageView(this);
i.setImageResource(R.drawable.my_image);
i.setContentDescription(getResources().getString(R.string.my_image_desc));

// set the ImageView bounds to match the Drawable's dimensions


i.setAdjustViewBounds(true);
i.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// Add the ImageView to the layout and set the layout as the content view.
constraintLayout.addView(i);
setContentView(constraintLayout);
}
Create drawables from XML resources
If there is a Drawable object that you'd like to create, which isn't initially dependent on
variables defined by your code or user interaction, then defining the Drawable in XML is a
good option. Even if you expect your Drawable to change its properties during the user's
interaction with your app, you should consider defining the object in XML, as you can
modify properties after it's instantiated.
After you've defined your Drawable in XML, save the file in the res/drawable/ directory of
your project. The following example shows the XML that defines
a TransitionDrawable resource, which inherits from Drawable:
<!-- res/drawable/expand_collapse.xml -->
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image_expand"/>

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 14


MC4204_Mobile Application Development Unit-5

<item android:drawable="@drawable/image_collapse"/>
</transition>

Then, retrieve and instantiate the object by calling Resources.getDrawable(), and passing the
resource ID of your XML file. Any Drawable subclass that supports the inflate() method can
be defined in XML and instantiated by your app. Each drawable class that supports XML
inflation utilizes specific XML attributes that help define the object properties. The following
code instantiates the TransitionDrawable and sets it as the content of an ImageView object:
Resources res = context.getResources();
TransitionDrawable transition =
(TransitionDrawable) ResourcesCompat.getDrawable(res, R.drawable.expand_collapse,
null);
ImageView image = (ImageView) findViewById(R.id.toggle_image);
image.setImageDrawable(transition);
// Description of the initial state that the drawable represents.
image.setContentDescription(getResources().getString(R.string.collapsed));

// Then you can call the TransitionDrawable object's methods.


transition.startTransition(1000);

// After the transition is complete, change the image's content description


// to reflect the new state.
Shape drawables
A ShapeDrawable object can be a good option when you want to dynamically draw a two-
dimensional graphic. You can programmatically draw primitive shapes on
a ShapeDrawable object and apply the styles that your app needs.
ShapeDrawable is a subclass of Drawable. For this reason, you can use
a ShapeDrawable wherever a Drawable is expected. For example, you can use
a ShapeDrawable object to set the background of a view by passing it to
the setBackgroundDrawable() method of the view. You can also draw your shape as its own
custom view and add it to a layout in your app.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 15


MC4204_Mobile Application Development Unit-5

Because ShapeDrawable has its own draw() method, you can create a subclass of View that
draws the ShapeDrawable object during the onDraw() event, as shown in the following code
example:
public class CustomDrawableView extends View {
private ShapeDrawable drawable;

public CustomDrawableView(Context context) {


super(context);
int x = 10;
int y = 10;
int width = 300;
int height = 50;
setContentDescription(context.getResources().getString(
R.string.my_view_desc));
drawable = new ShapeDrawable(new OvalShape());
// If the color isn't set, the shape uses black as the default.
drawable.getPaint().setColor(0xff74AC23);
// If the bounds aren't set, the shape can't be drawn.
drawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas) {
drawable.draw(canvas);
}}
NinePatch drawables
A NinePatchDrawable graphic is a stretchable bitmap image that you can use as the
background of a view. Android automatically resizes the graphic to accommodate the
contents of the view. An example use of a NinePatch image is the background used by
standard Android buttons—buttons must stretch to accommodate strings of various lengths. A
NinePatch graphic is a standard PNG image that includes an extra 1-pixel border. It must be
saved with the 9.png extension in the res/drawable/ directory of your project.
Figure 1 shows an example of a NinePatch graphic used to define a button:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 16


MC4204_Mobile Application Development Unit-5

Figure 1: Example of a NinePatch graphic that defines a button


This NinePatch graphic defines one stretchable area with the left and top lines, and the
drawable area with the bottom and right lines. In the top image, the dotted grey lines identify
the regions of the image that are replicated in order to stretch the image.
The following sample layout XML demonstrates how to add a NinePatch graphic to a couple
of buttons. The NinePatch image is saved to res/drawable/my_button_background.9.png.
<Button android:id="@+id/tiny"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:text="Tiny"
android:textSize="8sp"
android:background="@drawable/my_button_background"/>
<Button android:id="@+id/big"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:text="Biiiiiiig text!"

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 17


MC4204_Mobile Application Development Unit-5

android:textSize="30sp"
android:background="@drawable/my_button_background"/>
Custom drawables
When you want to create some custom drawings, you can do so by extending
the Drawable class (or any of its subclasses).
The most important method to implement is draw(Canvas) because this provides
the Canvas object you must use to provide your drawing instructions.
The following code shows a simple subclass of Drawable that draws a circle:
public class MyDrawable extends Drawable {
private final Paint redPaint;
public MyDrawable() {
// Set up color and text size
redPaint = new Paint();
redPaint.setARGB(255, 255, 0, 0);
}
@Override
public void draw(Canvas canvas) {
// Get the drawable's bounds
int width = getBounds().width();
int height = getBounds().height();
float radius = Math.min(width, height) / 2;
// Draw a red circle in the center
canvas.drawCircle(width/2, height/2, radius, redPaint);
}
@Override
public void setAlpha(int alpha) {
// This method is required
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
// This method is required
}
@Override

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 18


MC4204_Mobile Application Development Unit-5

public int getOpacity() {


// Must be PixelFormat.UNKNOWN, TRANSLUCENT, TRANSPARENT, or
OPAQUE
return PixelFormat.OPAQUE;
}}
Vector drawables overview
A VectorDrawable is a vector graphic defined in an XML file as a set of points, lines,
and curves along with its associated color information. The major advantage of using a vector
drawable is image scalability. It can be scaled without loss of display quality, which means
the same file is resized for different screen densities without loss of image quality. This
results in smaller APK files and less developer maintenance. You can also use vector images
for animation by using multiple XML files instead of multiple images for each display
resolution.
Android 5.0 (API level 21) was the first version to officially support vector drawables
with VectorDrawable and AnimatedVectorDrawable, but you can support older versions with
the Android support library, which provides the VectorDrawableCompat and
AnimatedVectorDrawableCompat classes.
About VectorDrawable class
VectorDrawable defines a static drawable object. Similar to the SVG format, each vector
graphic is defined as a tree hierachy, which is made up of path and group objects.
Each path contains the geometry of the object's outline and group contains details for
transformation. All paths are drawn in the same order as they appear in the XML file.

Figure 1. Sample hierarchy of a vector drawable asset


The Vector asset studio tool offers a simple way to add a vector graphic to the project as an
XML file.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 19


MC4204_Mobile Application Development Unit-5

Example XML
Here is a sample VectorDrawable XML file that renders an image of a battery in the charging
mode.
<!-- res/drawable/battery_charging.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
<!-- intrinsic size of the drawable -->
android:height="24dp"
android:width="24dp"
<!-- size of the virtual canvas -->
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<group
android:name="rotationGroup"
android:pivotX="10.0"
android:pivotY="10.0"
android:rotation="15.0" >
<path
android:name="vect"
android:fillColor="#FF000000"
android:pathData="M15.67,4H14V2h-4v2H8.33C7.6,4 7,4.6
7,5.33V9h4.93L13,7v2h4V5.33C17,4.6 16.4,4 15.67,4z"
android:fillAlpha=".3"/>
<path
android:name="draw"
android:fillColor="#FF000000"
android:pathData="M13,12.5h2L11,20v-5.5H9L11.93,9H7v11.67C7,21.4 7.6,22
8.33,22h7.33c0.74,0 1.34,-0.6 1.34,-1.33V9h-4v3.5z"/>
</group>
</vector>

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 20


MC4204_Mobile Application Development Unit-5

This XML renders the following image:

About AnimatedVectorDrawable class


AnimatedVectorDrawable adds animation to the properties of a vector graphic. You can
define an animated vector graphic as three separate resource files or as a single XML file
defining the entire drawable. Let's look at both the approaches for better
understanding: Multiple XML files and Single XML file.
Multiple XML files
By using this approach, you can define three separate XML files:
 A VectorDrawable XML file.
 An AnimatedVectorDrawable XML file that defines the target VectorDrawable, the target
paths and groups to animate, the properties, and the animations defined
as ObjectAnimator objects or AnimatorSet objects.
 An animator XML file.
Example of multiple XML files
The following XML files demonstrate the animation of a vector graphic.
 VectorDrawable's XML file: vd.xml
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="64dp"
android:width="64dp"
android:viewportHeight="600"
android:viewportWidth="600" >
<group
android:name="rotationGroup"
android:pivotX="300.0"
android:pivotY="300.0"
android:rotation="45.0" >
<path
android:name="vectorPath"
android:fillColor="#000000"

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 21


MC4204_Mobile Application Development Unit-5

android:pathData="M300,70 l 0,-70 70,70 0,0 -70,70z" />


</group>
</vector>

 AnimatedVectorDrawable's XML file: avd.xml


 <animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/vd" >
<target
android:name="rotationGroup"
android:animation="@anim/rotation" />
<target
android:name="vectorPath"
android:animation="@anim/path_morph" />
</animated-vector>

 Animator XML files that are used in the AnimatedVectorDrawable's XML


file: rotation.xml and path_morph.xml
Single XML file
By using this approach, you can merge the related XML files into a single XML file through
the XML Bundle Format. At the time of building the app, the aapt tag creates separate
resources and references them in the animated vector. This approach requires Build Tools 24
or higher, and the output is backward compatible.
Example of a single XML file
<animated-vector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt">
<aapt:attr name="android:drawable">
<vector
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 22


MC4204_Mobile Application Development Unit-5

android:name="root"
android:strokeWidth="2"
android:strokeLineCap="square"
android:strokeColor="?android:colorControlNormal"
android:pathData="M4.8,13.4 L9,17.6 M10.4,16.2 L19.6,7" />
</vector>
</aapt:attr>
<target android:name="root">
<aapt:attr name="android:animation">
<objectAnimator
android:propertyName="pathData"
android:valueFrom="M4.8,13.4 L9,17.6 M10.4,16.2 L19.6,7"
android:valueTo="M6.4,6.4 L17.6,17.6 M6.4,17.6 L17.6,6.4"
android:duration="300"
android:interpolator="@android:interpolator/fast_out_slow_in"
android:valueType="pathType" />
</aapt:attr>
</target>
</animated-vector>
How to handle the bitmaps. Explain it.
Handling bitmaps
 Bitmaps can very easily exhaust an app's memory budget. For example, the camera on
the Pixel phone takes photos of up to 4048x3036 pixels (12 megapixels). If the bitmap
configuration used is ARGB_8888, the default for Android 2.3 (API level 9) and higher,
loading a single photo into memory takes about 48MB of memory (4048*3036*4 bytes).
Such a large memory demand can immediately use up all the memory available to the app.
 Loading bitmaps on the UI thread can degrade your app's performance, causing slow
responsiveness or even ANR messages. It is therefore important to manage threading
appropriately when working with bitmaps.
 If your app is loading multiple bitmaps into memory, you need to skillfully manage memory
and disk caching. Otherwise, the responsiveness and fluidity of your app's UI may suffer.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 23


MC4204_Mobile Application Development Unit-5

OpenGL ES
Android includes support for high performance 2D and 3D graphics with the Open Graphics
Library (OpenGL®), specifically, the OpenGL ES API. OpenGL is a cross-platform graphics
API that specifies a standard software interface for 3D graphics processing hardware.
OpenGL ES is a flavor of the OpenGL specification intended for embedded devices. Android
supports several versions of the OpenGL ES API:
 OpenGL ES 1.0 and 1.1 - This API specification is supported by Android 1.0 and higher.
 OpenGL ES 2.0 - This API specification is supported by Android 2.2 (API level 8) and
higher.
 OpenGL ES 3.0 - This API specification is supported by Android 4.3 (API level 18) and
higher.
 OpenGL ES 3.1 - This API specification is supported by Android 5.0 (API level 21) and
higher.
Displaying graphics with OpenGL ES
The Android framework provides plenty of standard tools for creating attractive, functional
graphical user interfaces. However, if you want more control of what your application draws
on screen, or are venturing into three dimensional graphics, you need to use a different tool.
The OpenGL ES APIs provided by the Android framework offers a set of tools for displaying
high-end, animated graphics that are limited only by your imagination and can also benefit
from the acceleration of graphics processing units (GPUs) provided on many Android
devices.
This class walks you through the basics of developing applications that use OpenGL,
including setup, drawing objects, moving drawn elements and responding to touch input.
The example code in this class uses the OpenGL ES 2.0 APIs, which is the recommended
API version to use with current Android devices. For more information about versions of
OpenGL ES, see the OpenGL developer guide.
Define shapes
OpenGL ES coordinate system relative to an Android device screen, the basics of defining a
shape, shape faces, as well as defining a triangle and a square.
Define a triangle
OpenGL ES allows you to define drawn objects using coordinates in three-dimensional
space. So, before you can draw a triangle, you must define its coordinates. In OpenGL, the
typical way to do this is to define a vertex array of floating point numbers for the coordinates.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 24


MC4204_Mobile Application Development Unit-5

For maximum efficiency, you write these coordinates into a ByteBuffer, that is passed into
the OpenGL ES graphics pipeline for processing.
public class Triangle {
private FloatBuffer vertexBuffer;
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float triangleCoords[] = { // in counterclockwise order:
0.0f, 0.622008459f, 0.0f, // top
-0.5f, -0.311004243f, 0.0f, // bottom left
0.5f, -0.311004243f, 0.0f // bottom right
};
// Set color with red, green, blue and alpha (opacity) values
float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };
public Triangle() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
triangleCoords.length * 4);
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
// create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer();
// add the coordinates to the FloatBuffer
vertexBuffer.put(triangleCoords);
// set the buffer to read the first coordinate
vertexBuffer.position(0);
}}
Define a square
Defining triangles is pretty easy in OpenGL, but what if you want to get a just a little more
complex? Say, a square? There are a number of ways to do this, but a typical path to drawing
such a shape in OpenGL ES is to use two triangles drawn together:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 25


MC4204_Mobile Application Development Unit-5

Figure 1. Drawing a square using two triangles.


Again, you should define the vertices in a counterclockwise order for both triangles that
represent this shape, and put the values in a ByteBuffer. In order to avoid defining the two
coordinates shared by each triangle twice, use a drawing list to tell the OpenGL ES graphics
pipeline how to draw these vertices. Here’s the code for this shape:
public class Square {
private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float squareCoords[] = {
-0.5f, 0.5f, 0.0f, // top left
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, // bottom right
0.5f, 0.5f, 0.0f }; // top right
private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices
public Square() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (# of coordinate values * 4 bytes per float)
squareCoords.length * 4);
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(squareCoords);

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 26


MC4204_Mobile Application Development Unit-5

vertexBuffer.position(0);
// initialize byte buffer for the draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(
// (# of coordinate values * 2 bytes per short)
drawOrder.length * 2);
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);
}}

This example gives you a peek at what it takes to create more complex shapes with OpenGL.
In general, you use collections of triangles to draw objects. In the next lesson, you learn how
to draw these shapes on screen.
Draw shapes
Initialize shapes
Before you do any drawing, you must initialize and load the shapes you plan to draw. Unless
the structure (the original coordinates) of the shapes you use in your program change during
the course of execution, you should initialize them in the onSurfaceCreated() method of your
renderer for memory and processing efficiency.
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
private Triangle mTriangle;
private Square mSquare;

public void onSurfaceCreated(GL10 unused, EGLConfig config) {


...
// initialize a triangle
mTriangle = new Triangle();
// initialize a square
mSquare = new Square();
}
...

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 27


MC4204_Mobile Application Development Unit-5

Draw a shape
Drawing a defined shape using OpenGL ES 2.0 requires a significant amount of code,
because you must provide a lot of details to the graphics rendering pipeline. Specifically, you
must define the following:
 Vertex Shader - OpenGL ES graphics code for rendering the vertices of a shape.
 Fragment Shader - OpenGL ES code for rendering the face of a shape with colors or textures.
 Program - An OpenGL ES object that contains the shaders you want to use for drawing one
or more shapes.
You need at least one vertex shader to draw a shape and one fragment shader to color that
shape. These shaders must be compiled and then added to an OpenGL ES program, which is
then used to draw the shape. Here is an example of how to define basic shaders you can use
to draw a shape in the Triangle class:
public class Triangle {
private final String vertexShaderCode =
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";

private final String fragmentShaderCode =


"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";

...
}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 28


MC4204_Mobile Application Development Unit-5

Shaders contain OpenGL Shading Language (GLSL) code that must be compiled prior to
using it in the OpenGL ES environment. To compile this code, create a utility method in your
renderer class:
When you run the application, it should look something like this:

Figure 1. Triangle drawn without a projection or camera view.


Apply projection and camera views
In the OpenGL ES environment, projection and camera views allow you to display drawn
objects in a way that more closely resembles how you see physical objects with your eyes.
This simulation of physical viewing is done with mathematical transformations of drawn
object coordinates:
 Projection - This transformation adjusts the coordinates of drawn objects based on the width
and height of the GLSurfaceView where they are displayed. Without this calculation, objects
drawn by OpenGL ES are skewed by the unequal proportions of the view window. A
projection transformation typically only has to be calculated when the proportions of the
OpenGL view are established or changed in the onSurfaceChanged() method of your
renderer..
 Camera View - This transformation adjusts the coordinates of drawn objects based on a
virtual camera position. It’s important to note that OpenGL ES does not define an actual
camera object, but instead provides utility methods that simulate a camera by transforming
the display of drawn objects. A camera view transformation might be calculated only once

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 29


MC4204_Mobile Application Development Unit-5

when you establish your GLSurfaceView, or might change dynamically based on user actions
or your application’s function.
Add motion
OpenGL ES by learning how to add motion to a shape with rotation.
Rotate a shape
Rotating a drawing object with OpenGL ES 2.0 is relatively simple. In your renderer, create
another transformation matrix (a rotation matrix) and then combine it with your projection
and camera view transformation matrices:
private float[] rotationMatrix = new float[16];
@Override
public void onDrawFrame(GL10 gl) {
float[] scratch = new float[16];
...
// Create a rotation transformation for the triangle
long time = SystemClock.uptimeMillis() % 4000L;
float angle = 0.090f * ((int) time);
Matrix.setRotateM(rotationMatrix, 0, angle, 0, 0, -1.0f);
// Combine the rotation matrix with the projection and camera view
// Note that the vPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
Matrix.multiplyMM(scratch, 0, vPMatrix, 0, rotationMatrix, 0);
// Draw triangle
mTriangle.draw(scratch);
}
Enable continuous rendering
If you have diligently followed along with the example code in this class to this point, make
sure you comment out the line that sets the render mode only draw when dirty, otherwise
OpenGL rotates the shape only one increment and then waits for a call
to requestRender() from the GLSurfaceView container:
public class MyGLSurfaceView(Context context) extends GLSurfaceView {
...
// Render the view only when there is a change in the drawing data.
// To allow the triangle to rotate automatically, this line is commented out:

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 30


MC4204_Mobile Application Development Unit-5

//setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
Unless you have objects changing without any user interaction, it’s usually a good idea have
this flag turned on. Be ready to uncomment this code, because the next lesson makes this call
applicable once again.
Respond to touch events
Setup a touch listener
In order to make your OpenGL ES application respond to touch events, you must implement
the onTouchEvent() method in your GLSurfaceView class. The example implementation
below shows how to listen for MotionEvent.ACTION_MOVE events and translate them to
an angle of rotation for a shape.
private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private float previousX;
private float previousY;
@Override
public boolean onTouchEvent(MotionEvent e) {
// MotionEvent reports input details from the touch screen
// and other input controls. In this case, you are only
// interested in events where the touch position changed.
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:

float dx = x - previousX;
float dy = y - previousY;
// reverse direction of rotation above the mid-line
if (y > getHeight() / 2) {
dx = dx * -1 ;
}
// reverse direction of rotation to left of the mid-line
if (x < getWidth() / 2) {
dy = dy * -1 ;

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 31


MC4204_Mobile Application Development Unit-5

}
renderer.setAngle(
renderer.getAngle() +
((dx + dy) * TOUCH_SCALE_FACTOR));
requestRender();
}
previousX = x;
previousY = y;
return true;
}
Expose the rotation angle
The example code above requires that you expose the rotation angle through your renderer by
adding a public member. Since the renderer code is running on a separate thread from the
main user interface thread of your application, you must declare this public variable
as volatile. Here is the code to declare the variable and expose the getter and setter pair:
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
public volatile float mAngle;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}}

Apply rotation
To apply the rotation generated by touch input, comment out the code that generates an angle
and add a variable that contains the touch input generated angle:
public void onDrawFrame(GL10 gl) {
...
float[] scratch = new float[16];

// Create a rotation for the triangle

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 32


MC4204_Mobile Application Development Unit-5

// long time = SystemClock.uptimeMillis() % 4000L;


// float angle = 0.090f * ((int) time);
Matrix.setRotateM(rotationMatrix, 0, mAngle, 0, 0, -1.0f);
// Combine the rotation matrix with the projection and camera view
// Note that the vPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
Matrix.multiplyMM(scratch, 0, vPMatrix, 0, rotationMatrix, 0);
// Draw triangle
mTriangle.draw(scratch);
}
When you have completed the steps described above, run the program and drag your finger
over the screen to rotate the triangle:

Figure 1. Triangle being rotated with touch input (circle shows touch location).

Enhance graphics with wide color content


Android 8.0 (API level 26) introduced color management support for additional color
spaces besides standard RGB (sRGB) for rendering graphics on devices with compatible
displays. With this support, your app can render bitmaps with embedded wide color profiles
loaded from PNG, JPEG, and WebP files via Java or native code. Apps using OpenGL or

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 33


MC4204_Mobile Application Development Unit-5

Vulkan can directly output wide color gamut content (using Display P3 and scRGB). This
capability is useful for creating apps that involve high fidelity color reproduction, such as
image and video editing apps.
Render wide color gamut content

Figure 1. Display P3 (orange) vs. sRGB (white) color spaces


To render wide color gamut content, your app must load a wide color bitmap, that is a bitmap
with a color profile containing a color space wider than sRGB. Common wide color profiles
include Adobe RGB, DCI-P3 and Display P3.
Your app can query the color space of a bitmap, by calling getColorSpace(). To determine if
the system recognizes a specific color space to be wide gamut, you can call
the isWideGamut() method.
The Color class allows you to represent a color with four components packed into a 64-bit
long value, instead of the most common representation that uses an integer value. Using long
values, you can define colors with more precision than integer values. If you need to create or
encode a color as a long value, use one of the pack() methods in the Color class.
You can verify whether your app properly requested the wide color gamut mode, by checking
that the getColorMode() method returns COLOR_MODE_WIDE_COLOR_GAMUT (this
method does not indicate, however, whether the wide color gamut mode was actually
granted).

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 34


MC4204_Mobile Application Development Unit-5

Use wide color gamut support in native code


This section describes how to enable wide color gamut mode with
the OpenGL and Vulkan APIs if your app uses native code.
OpenGL
In order to use wide color gamut mode in OpenGL, your app must include the EGL 1.4
library with one of the following extensions:
 EGL_EXT_gl_colorspace_display_p3
 EGL_EXT_gl_colorspace_scrgb
 EGL_EXT_gl_colorspace_scrgb_linear
To enable the feature, you must first create a GL context via eglChooseConfig, with one of
the three supported color buffer formats for wide color in the attributes. The color buffer
format for wide color must be one of these sets of RGBA values:
 8, 8, 8, 8
 10, 10, 10, 2
 FP16, FP16, FP16, FP16
Then, request the P3 color space extension when creating your render targets, as shown in the
following code snippet:
std::vector<EGLint> attributes;
attributes.push_back(EGL_GL_COLORSPACE_KHR);
attributes.push_back(EGL_GL_COLORSPACE_DISPLAY_P3_EXT);
attributes.push_back(EGL_NONE);
engine->surface_ = eglCreateWindowSurface(
engine->display_, config, engine->app->window, attributes.data());

Vulkan
The Vulkan support for wide color gamut is provided through
the VK_EXT_swapchain_colorspace extension.
Before enabling wide color support in your Vulkan code, first check that the extension is
supported via vkEnumerateInstanceExtensionProperties. If the extension is available, you
must enable it during vkCreateInstance before creating any swapchain images that use the
additional color spaces defined by the extension.
Before creating the swapchain, you need choose your desired color space, then loop through
the available physical device surfaces and choose a valid color format for that color space.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 35


MC4204_Mobile Application Development Unit-5

On Android devices, Vulkan supports wide color gamut with the following color spaces
and VkSurfaceFormatKHR color formats:
 Vulkan wide color gamut color spaces:
 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT
 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT
 Vulkan color formats with wide color gamut support:
 VK_FORMAT_R16G16B16A16_SFLOAT
 VK_FORMAT_A2R10G10B10_UNORM_PACK32
 VK_FORMAT_R8G8B8A8_UNORM
The following code snippet shows how you can check that the device supports the Display P3
color space:
uint32_t formatCount = 0;
vkGetPhysicalDeviceSurfaceFormatsKHR(
vkPhysicalDev,
vkSurface,
&formatCount,
nullptr);
VkSurfaceFormatKHR *formats = new VkSurfaceFormatKHR[formatCount];
vkGetPhysicalDeviceSurfaceFormatsKHR(
vkPhysicalDev,
vkSurface,
&formatCount,
formats);

uint32_t displayP3Index = formatCount;


for (uint32_t idx = 0; idx < formatCount; idx++) {
if (formats[idx].format == requiredSwapChainFmt &&
formats[idx].colorSpace==VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT)
{
displayP3Index = idx;
break;
}
}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 36


MC4204_Mobile Application Development Unit-5

if (displayP3Index == formatCount) {
// Display P3 is not supported on the platform
// choose other format
}

The following code snippet shows how to request a Vulkan swapchain


with VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
uint32_t queueFamily = 0;
VkSwapchainCreateInfoKHR swapchainCreate {
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
.pNext = nullptr,
.surface = AndroidVkSurface_,
.minImageCount = surfaceCapabilities.minImageCount,
.imageFormat = requiredSwapChainFmt,
.imageColorSpace = VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT,
.imageExtent = surfaceCapabilities.currentExtent,
.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
.imageArrayLayers = 1,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 1,
.pQueueFamilyIndices = &queueFamily,
.presentMode = VK_PRESENT_MODE_FIFO_KHR,
.oldSwapchain = VK_NULL_HANDLE,
.clipped = VK_FALSE,
};
VkRresult status = vkCreateSwapchainKHR(
vkDevice,
&swapchainCreate,
nullptr,
&vkSwapchain);
if (status != VK_SUCCESS) {
// Display P3 is not supported

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 37


MC4204_Mobile Application Development Unit-5

return false;
}

5.4 Event Handling


Define Event Handling
Event handling comes with Event and Handling. The event here is nothing but
an Action. Handling here means managing. In the whole Android Event Handling, all we do
is manage the actions. These actions are related to the user’s interaction. These Events collect
data about the user’s interaction using interactive components.
To include the Event Handler in your application, you should know the following three
concepts:
 Event Listeners
 Event Handlers
 Event Listener Registration
Discuss in detail about the various categories of Events with example.
1. Event Listeners
An event listener is an interface in the View class of Android. It has a single callback
method. This method will be called when the View that is registered with the Listener is
activated by the user’s action.

Following are some of the important Event Listeners:

Event Listeners Event listener Description

This event occurs when the user clicks on an item on the screen in
onClick() touch more or focuses on an item using a trackball or navigation-
keys.

This event occurs when a user clicks on an item or screen for more
onLongClick()
than 1 second.

This event occurs when a user navigates away from an item that
onFocusChange()
was on focus.

onKey() This event occurs when a user focuses and clicks on an item.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 38


MC4204_Mobile Application Development Unit-5

This event occurs when a user touches a particular range of an item


onTouch()
with gestures or simple touch or tap.

onCreateContextMenu() This event occurs when a Context Menu is built.

onMenuItemClick() It occurs when a user clicks or selects an item from a menu.

2. Event Handlers
Event handles are the actual methods that have the action that is to be taken. After an event
has happened and event listeners are registered, event listeners call Event Handler. These are
useful to define some callback methods.
Following are some of the important Event Handlers:

Event Handler Event Handler Description

onKeyUp() The system invokes this method when a new key event occurs.

onKeyDown() The system invokes this method when a key down event occurs.

onTrackballEvent() The system invokes this method when a trackball motion event occurs.

onTouchEvent() The system invokes this method when some touch event occurs.

The system invokes this method when an item gets into focus or loses
onFocusChange()
focus.

3. Event Listener Registration


Event Registration is the process in which Event Listeners are registered with Event
Handlers. This is important as Handler will work only after the Listener fires an Event.
Android Event Listener registration can be done in the following three ways:
1. The first method to register event listeners is by directly mentioning them in
activity_main.xml.
2. We can also register event listeners by using Activity class that implements a
listener interface.
3. The last method is by using an Anonymous class.
4. The following is an example to demonstrate Event Listener Registration:

@Override
protected void onCreate(Bundle savedInstanceState) {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 39


MC4204_Mobile Application Development Unit-5

Button button = (Button)findViewById(R.id.btn1);


button.setOnTouchListener(buttonListener);
// code
}
// Anonymous implementation of OnTouchListener
private View.OnTouchListener buttonListener = new View.OnTouchListener() {
public void onTouchEvent(View v) {
// define the action
}
};

Touch mode
While a user interacts with the device they roll the screen over. Therefore it’s necessary to
focus on the items that are actionable. In the devices with touch functionality, and the
user begins interacting with it then it is not important to give focus on touchable items.
This mode of interaction is “Touch Mode”. Once a user touches the screen, the device
enters in touch mode and then onwards the actionable icons and buttons are kept on focus
like – navigation button or home button.
Handling Focus
The framework handles the focus movement according to user input. Handling the focus
includes adding and removing the focus according to the user input movements. Focus
changes with the help of Views. You can check if the View is set to be in focusable mode
or not using isFocusable(). And we can also change the focus mode by
using setFocusable().
We can set the focus of view in touch mode as well, using setFocusInTouchMode(). To
check if a view allows focus in touch mode use isFocusableInTouchMode().
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


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

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 40


MC4204_Mobile Application Development Unit-5

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DataFlair "/>
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Event" />
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="See me! />
</LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


Button btn;
TextView tView;

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 41


MC4204_Mobile Application Development Unit-5

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btnClick);
tView = (TextView)findViewById(R.id.txtResult);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setText("You've Clicked \n The Event has taken place");
txtView.setTextSize(25);
txtView.setGravity(Gravity.CENTER);
txtView.setTextColor(R.color.colorAccent);
}
});
}
}

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 42


MC4204_Mobile Application Development Unit-5

5.5 Telephony and Location Based Services


Write a short on Telephony
The Telephony provider contains data related to phone operation, specifically SMS and
MMS messages, access to the APN list, including the MMSC to use, and the service state.
Creating an SMS app
Only the default SMS app (selected by the user in system settings) is able to write to the SMS
Provider (the tables defined within the Telephony class) and only the default SMS app
receives the Telephony.Sms.Intents.SMS_DELIVER_ACTION broadcast when the user
receives an SMS or the Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION broadcast
when the user receives an MMS.
Any app that wants to behave as the user's default SMS app must handle the following
intents:
 In a broadcast receiver, include an intent filter
for Telephony.Sms.Intents.SMS_DELIVER_ACTION ("android.provider.Telephony.SMS_
DELIVER"). The broadcast receiver must also require
the Manifest.permission.BROADCAST_SMS permission.
This allows your app to directly receive incoming SMS messages.
 In a broadcast receiver, include an intent filter
for Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION}
("android.provider.Telephony.WAP_PUSH_DELIVER") with the MIME
type "application/vnd.wap.mms-message". The broadcast receiver must also require
the Manifest.permission.BROADCAST_WAP_PUSH permission.
This allows your app to directly receive incoming MMS messages.
 In your activity that delivers new messages, include an intent filter
for Intent.ACTION_SENDTO ("android.intent.action.SENDTO" ) with
schemas, sms:, smsto:, mms:, and mmsto:.
This allows your app to receive intents from other apps that want to deliver a message.
 In a service, include an intent filter
for TelephonyManager.ACTION_RESPOND_VIA_MESSAGE ("android.intent.action.RES
POND_VIA_MESSAGE") with schemas, sms:, smsto:, mms:, and mmsto:. This service must
also require the Manifest.permission.SEND_RESPOND_VIA_MESSAGE permission.
This allows users to respond to incoming phone calls with an immediate text message using
your app.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 43


MC4204_Mobile Application Development Unit-5

Other apps that are not selected as the default SMS app can only read the SMS Provider, but
may also be notified when a new SMS arrives by listening for
the Telephony.Sms.Intents.SMS_RECEIVED_ACTION broadcast, which is a non-abortable
broadcast that may be delivered to multiple apps. This broadcast is intended for apps that—
while not selected as the default SMS app—need to read special incoming messages such as
to perform phone number verification.
Write a brief note on Location Based Services
Location Based Services

Android location APIs make it easy for you to build location-aware applications,
without needing to focus on the details of the underlying location technology.

This becomes possible with the help of Google Play services, which facilitates
adding location awareness to your app with automated location tracking, geofencing, and
activity recognition.

The Location Object


The Location object represents a geographic location which can consist of a latitude,
longitude, time stamp, and other information such as bearing, altitude and velocity. There
are following important methods which you can use with Location object to get location
specific information −

Sr.No. Method & Description

1
float distanceTo(Location dest)

Returns the approximate distance in meters between this location and the given location.

2
float getAccuracy()

Get the estimated accuracy of this location, in meters.

3
double getAltitude()

Get the altitude if available, in meters above sea level.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 44


MC4204_Mobile Application Development Unit-5

4
float getBearing()

Get the bearing, in degrees.

5
double getLatitude()

Get the latitude, in degrees.

6
double getLongitude()

Get the longitude, in degrees.

7
float getSpeed()

Get the speed if it is available, in meters/second over ground.

8
boolean hasAccuracy()

True if this location has an accuracy.

9
boolean hasAltitude()

True if this location has an altitude.

10
boolean hasBearing()

True if this location has a bearing.

11
boolean hasSpeed()

True if this location has a speed.

12
void reset()

Clears the contents of the location.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 45


MC4204_Mobile Application Development Unit-5

13
void setAccuracy(float accuracy)

Set the estimated accuracy of this location, meters.

14
void setAltitude(double altitude)

Set the altitude, in meters above sea level.

15
void setBearing(float bearing)

Set the bearing, in degrees.

16
void setLatitude(double latitude)

Set the latitude, in degrees.

17
void setLongitude(double longitude)

Set the longitude, in degrees.

18
void setSpeed(float speed)

Set the speed, in meters/second over ground.

19
String toString()

Returns a string containing a concise, human-readable description of this object.

Get the Current Location

To get the current location, create a location client which is LocationClient object, connect
it to Location Services using connect() method, and then call its getLastLocation() method.
This method returns the most recent location in the form of Location object that contains
latitude and longitude coordinates and other information as explained above. To have
location based functionality in your activity, you will have to implement two interfaces −

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 46


MC4204_Mobile Application Development Unit-5

 GooglePlayServicesClient.ConnectionCallbacks

 GooglePlayServicesClient.OnConnectionFailedListener

These interfaces provide following important callback methods, which you need to
implement in your activity class −

Sr.No. Callback Methods & Description

1
abstract void onConnected(Bundle connectionHint)

This callback method is called when location service is connected to the location client
successfully. You will use connect() method to connect to the location client.

2
abstract void onDisconnected()

This callback method is called when the client is disconnected. You will
use disconnect() method to disconnect from the location client.

3
abstract void onConnectionFailed(ConnectionResult result)

This callback method is called when there was an error connecting the client to the
service.

You should create the location client in onCreate() method of your activity class, then
connect it in onStart(), so that Location Services maintains the current location while your
activity is fully visible. You should disconnect the client in onStop() method, so that when
your app is not visible, Location Services is not maintaining the current location. This helps
in saving battery power up-to a large extent.

Get the Updated Location

If you are willing to have location updates, then apart from above mentioned interfaces, you
will need to implement LocationListener interface as well. This interface provide following
callback method, which you need to implement in your activity class −

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 47


MC4204_Mobile Application Development Unit-5

Sr.No. Callback Method & Description

1
abstract void onLocationChanged(Location location)

This callback method is used for receiving notifications from the LocationClient when the
location has changed.

Location Quality of Service

The LocationRequest object is used to request a quality of service (QoS) for location
updates from the LocationClient. There are following useful setter methods which you can
use to handle QoS. There are equivalent getter methods available which you can check in
Android official documentation.

Sr.No. Method & Description

1
setExpirationDuration(long millis)

Set the duration of this request, in milliseconds.

2
setExpirationTime(long millis)

Set the request expiration time, in millisecond since boot.

3
setFastestInterval(long millis)

Explicitly set the fastest interval for location updates, in milliseconds.

4
setInterval(long millis)

Set the desired interval for active location updates, in milliseconds.

5
setNumUpdates(int numUpdates)

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 48


MC4204_Mobile Application Development Unit-5

Set the number of location updates.

6
setPriority(int priority)

Set the priority of the request.

Now for example, if your application wants high accuracy location it should create a
location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY
and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities
like PRIORITY_LOW_POWER for to request "city" level accuracy or
PRIORITY_BALANCED_POWER_ACCURACY for "block" level accuracy.

Activities should strongly consider removing all location request when entering the
background (for example at onPause()), or at least swap the request to a larger interval and
lower quality to save power consumption.

Displaying a Location Address

Once you have Location object, you can use Geocoder.getFromLocation() method to get
an address for a given latitude and longitude. This method is synchronous, and may take a
long time to do its work, so you should call the method from the doInBackground() method
of an AsyncTask class.

The AsyncTask must be subclassed to be used and the subclass will


override doInBackground(Params...) method to perform a task in the background
and onPostExecute(Result) method is invoked on the UI thread after the background
computation finishes and at the time to display the result. There is one more important
method available in AyncTask which is execute(Params... params), this method executes
the task with the specified parameters.

Example

Following example shows you in practical how to to use Location Services in your app to
get the current location and its equivalent addresses etc.

To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 49


MC4204_Mobile Application Development Unit-5

Create Android Application

Step Description

1 You will use Android studio IDE to create an Android application and name it
as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.

2 add src/GPSTracker.java file and add required code.

3 Modify src/MainActivity.java file and add required code as shown below to take care of
getting current location and its equivalent address.

4 Modify layout XML file res/layout/activity_main.xml to add all GUI components which
include three buttons and two text views to show location/address.

5 Modify res/values/strings.xml to define required constant values

6 Modify AndroidManifest.xml as shown below

7 Run the application to launch Android emulator and verify the result of the changes done in
the application.

Following is the content of the modified main activity file MainActivity.java.

package com.example.tutorialspoint7.myapplication;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 50


MC4204_Mobile Application Development Unit-5

import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

// GPSTracker class
GPSTracker gps;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{mPermission},
REQUEST_CODE_PERMISSION);
// If any permission above not allowed by user, this condition will
execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}
btnShowLocation = (Button) findViewById(R.id.button);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 51


MC4204_Mobile Application Development Unit-5

// create class object


gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: "
+ latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
} } }); }
}

Following is the content of the modified main activity file GPSTracker.java.

package com.example.tutorialspoint7.myapplication;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 52


MC4204_Mobile Application Development Unit-5

// flag for GPS status


boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 53


MC4204_Mobile Application Development Unit-5

// First get location from Network Provider


if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} } }

// if GPS Enabled get lat/long using GPS Services


if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("GPS Enabled", "GPS Enabled");


if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 54


MC4204_Mobile Application Development Unit-5

} } } } }
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 55


MC4204_Mobile Application Development Unit-5

return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
} });
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 56


MC4204_Mobile Application Development Unit-5

alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

Following will be the content of res/layout/activity_main.xml file −

<?xml version = "1.0" encoding = "utf-8"?>


<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:orientation = "vertical" >
<Button
android:id = "@+id/button"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "getlocation"/>
</LinearLayout>

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 57


MC4204_Mobile Application Development Unit-5

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version = "1.0" encoding = "utf-8"?>


<resources>
<string name = "app_name">Tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml −

<?xml version = "1.0" encoding = "utf-8"?>


<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.tutorialspoint7.myapplication">
<uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name = "android.permission.INTERNET" />
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />

<category android:name = "android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
</manifest>

Let's try to run your Tutorialspoint application. I assume that, you have connected your
actual Android Mobile device with your computer. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar. Before

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 58


MC4204_Mobile Application Development Unit-5

starting your application, Android studio installer will display following window to select an
option where you want to run your Android application.

Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 59

You might also like