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

MAD

Mad 6th sem Computer engineering polytechnic book
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)
37 views

MAD

Mad 6th sem Computer engineering polytechnic book
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/ 226

SUBJECT CODE : 22617

As per Revised Syllabus of

MSBTE - I Scheme
T.Y. Diploma Semester - VI
Computer Engineering Program Group
(CO / CM / IF / CW)

Mobile Application
Development
Vrushali R. Sonar
M.E. (IT), B.E. (Computer),
Lecturer, AISSMS’s Polytechnic,
Pune.

Narendra S. Joshi
Ph.D. (Pursuing), M.E. (CSE),
SOCSE Department
Assistant Professor,
Sandip University, Nashik.

Aniruddha D. Talole
M.E. (Computer Engg.), B.E. (Computer),
Lecturer(Computer Technology Department),
K. K. Wagh Polytechnic, Nashik.

® ®
TECHNICAL
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge

(i)
Mobile Application Development
Subject Code : 22617

T.Y. Diploma Semester - VI


Computer Engineering Program Group (CO / CM / IF / CW)

First Edition : January 2020

ã Copyright with Authors


All publishing rights (printed and ebook version) reserved with Technical Publications. No part of this book
should be reproduced in any form, Electronic, Mechanical, Photocopy or any information storage and
retrieval system without prior permission in writing, from Technical Publications, Pune.

Published by :
® ®
Amit Residency, Office No.1, 412, Shaniwar Peth, Pune - 411030, M.S. INDIA
TECHNICAL P h . : + 9 1 - 0 2 0 - 2 4 4 9 5 4 9 6 / 9 7 , Te l e f a x : + 9 1 - 0 2 0 - 2 4 4 9 5 4 9 7
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge Email : [email protected] Website : www.technicalpublications.org

ISBN 978-93-89750-07-2

9 789389 750072 MSBTE I

9789389750072 [1] (ii)


Syllabus
Mobile Application Development (22617)
Teaching Examination Scheme
Scheme

Credit Theory Practical


(L+T+P)
L T P Paper ESE PA Total ESE PA Total
Hrs.
Max Min Max Min Max Min Max Min Max Min Max Min

3 - 4 7 3 70 28 30* 00 100 40 25# 10 25 10 50 20

Unit Unit Outcomes (UOs) Topics and Sub - topics


(in cognitive domain)
Unit - I 1a. Explain the given basic terms 1.1 Introduction to Android, open handset
Android and its related to Android system. alliance, Android Ecosystem.
Tools 1b. Explain with sketches Android 1.2 Need of Android, Featutes of Android.
architecture for the given 1.3 Tools and software required for
application. developing an Android Application.
1c. Indentify tools and software 1.4 Android Architecture.
required for developing the given
Android application with
justification.
1d. Explain significance of the given
component in Android
architecture.
Unit - II 2a. Describe function of the given 2.1 Operating system, Java JDK, Android
Installation and component to operate the SDK.
configuration of specified IDE. 2.2 Android Development Tools (ADT)
Android 2b. Explain the given term related to
2.3 Android Virtual Devices (AVDs)
virtual machine.
2.4 Emulators
2c. Explain the given basic term
related to Android development 2.5 Dalvik Virtual Machine, Difference
tools. between JVM and DVM.
2d. Describe the features of given 2.6 Steps to install configure Android Studio
android emulator. and SDK.
2e. Describe the steps to configure
the given android development
environment.

(iv)
Unit-III 3a. Explain with relevant analogy the 3.1 Control flow, Directory Structure.
UI given Directory Structure. 3.2 Components of a screen, Fundamental
Components and 3b. Describe the steps to use the UI design.
Layouts given Android rich UI componet. 3.3. Linear Layout ; Absolute Layout, Frame
3c. Describe the steps to use the Layout, Table Layout ; Relative Layout.
given type of Layout.
3d. Develop the given basic Android
application.
Unit-IV 4a. Develop rich user Interfaces for 4.1 Text view, Edit Text; Button Image
Designing User the given Android application. Button; Toggle Button; Radio Button and
Interface with 4b. Develop Android application Radio Grop; Checkbox; Progress Bar
View using the given view. 4.2 List view ; Grid view ; Image view ;
4c. Explain the significance of the Scroll view ; Custom Toast Alert.
given display Alert. 4.3 Time and Date Picker.
4d. Develop the given application
using time and date picker.

Unit-V 5a. Apply the given Intents and 5.1 Intent, Intent_Filter
Activity And service in Application 5.2 Activity, Lifecycle; Broadcast Lifecycle.
Multimedia with development.
databases 5.3 Content Provider ; Fragments.
5b. Use Fragment to generate the
given multiple activities. 5.4 Service : Features of Service, Android
platform service, Defining new service,
5c. Develop programs to play the Service Lifecycle, Permission, example of
given multimedia. service.
5d. Write the query to perform the 5.5 Android System Architecture,
given database management Multimedia framework, Play Audio and
operation. Video, Text to speech, Sensors, Async
tasks.
5.6 Audio capture, Camera.
5.7 Bluetooth, Animation.
5.8 SQLite Database, necessity of SQLite,
Creation and connection of the database,
extracting value from cursors,
Transactions.

(v)
Unit-VI 6a. Explain the given location based 6.1 SMS Telephony
Security and service. 6.2 Location Based Sevices : Creating the
Application 6b. Write the steps to customize the project, Getting the maps API key,
Deployment given permissions for users. Displaying the map, Displaying the
6c. Explain features of the given zoom control, Navigating to a specific
android scecurity service. location, Adding markers, Getting
location, Geocoding and reverse
6d. Write the steps to publish the Geocoding, Getting Location data,
given android App. Monitoring Location.
6.3 Android Security Model, Declaring and
Using Permissions, Using Custom
Permission.
6.4 Application Deployment : Creating
Small Application, Signing of
application, Deploying app on Google
Play Store, Become a Publisher,
Developer Console.

(vi)
Table of Contents
2.6.5 Installation of Emulators. . . . . . . . . . . . . . 2 - 18
Unit - I
Unit - III
Chapter - 1 Android and its Tools
(1 - 1) to (1 - 12)
Chapter - 3 Components and Layouts
(3 - 1) to (3 - 66)
1.1 Introduction to Android . . . . . . . . . . . . . . . . . . 1 - 1
1.1.1 What is Android ? . . . . . . . . . . . . . . . . . . . 1 - 1
3.1 The Development Process. . . . . . . . . . . . . . . . . 3 - 1
1.1.2 Key Platform Components. . . . . . . . . . . . . 1 - 1 3.1.1 Creating the Project . . . . . . . . . . . . . . . . . . . 3 - 2
1.1.3 Android Versions . . . . . . . . . . . . . . . . . . . . 1 - 2 3.1.2 Directory and File Structure of an
Android Studio Project. . . . . . . . . . . . . . . 3 - 12
1.1.4 Open Handset Alliance (OHA) . . . . . . . . . 1 - 3
3.2 Components of Android Application . . . . . . . 3 - 16
1.1.5 Android Ecosystem . . . . . . . . . . . . . . . . . . 1 - 4
3.2.1 Creating the user Interface . . . . . . . . . . . . 3 - 18
1.1.6 Need of Android. . . . . . . . . . . . . . . . . . . . . 1 - 5 3.3 Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 19
1.2 Android Features. . . . . . . . . . . . . . . . . . . . . . . . 1 - 6 3.3.1 Android Linear Layout . . . . . . . . . . . . . . . 3 - 21
1.3 Tools and Software Required for 3.3.2 Android Absolute Layout. . . . . . . . . . . . . . 3 - 33
Developing an Android Application . . . . . . . . 1 - 7
3.3.3 Android Frame Layout . . . . . . . . . . . . . . . 3 - 36
1.4 Android Architecture . . . . . . . . . . . . . . . . . . . . 1 - 8 3.3.4 Android Table Layout . . . . . . . . . . . . . . . . 3 - 43

Unit - II 3.3.5 Android Relative Layout . . . . . . . . . . . . . . 3 - 52

Unit - IV
Chapter - 2 Installation and Configuration
of Android (2 - 1) to (2 - 20)
Chapter - 4 Designing User Interface with
2.1 The Android Operating System . . . . . . . . . . . . . 2 - 1 View (4 - 1) to (4 - 34)
2.1.1 How do Android Apps Work ? . . . . . . . . . . 2 - 1
4.1 The Android View . . . . . . . . . . . . . . . . . . . . . . 4 - 1
2.1.2 Java Development Kit (JDK) . . . . . . . . . . . 2 - 3
4.1.1 Basic Views . . . . . . . . . . . . . . . . . . . . . . . . 4 - 1
2.1.3 Android SDK . . . . . . . . . . . . . . . . . . . . . . . 2 - 4 4.1.1.1 Text View . . . . . . . . . . . . . . . . . . . . . 4 - 2
2.2 Android - Developer Tools . . . . . . . . . . . . . . . . 2 - 4
4.1.1.2 Declare UI Elements in XML . . . . . . 4 - 2
2.3 Android Virtual Device (AVD) . . . . . . . . . . . . . 2 - 5 4.1.2 Edit Text. . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 2
2.4 Android Emulator . . . . . . . . . . . . . . . . . . . . . . . 2 - 7 4.1.3 Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 6

2.5 Dalvik Virtual Machine (DVM) . . . . . . . . . . . . 2 - 7 4.1.3.1 Button Attributes . . . . . . . . . . . . . . . 4 - 7


4.1.4 Image Button . . . . . . . . . . . . . . . . . . . . . . . 4 - 7
2.6 Steps to Install and Configure
Android Studio and SDK . . . . . . . . . . . . . . . . . . 2 - 9 4.1.4.1 Image Button Attributes . . . . . . . . . . 4 - 8
2.6.1 The development environment . . . . . . . . . . 2 - 9 4.1.5 Toggle Button . . . . . . . . . . . . . . . . . . . . . . 4 - 8

2.6.2 Installing the Java Development Kit (JDK) 2 - 9 4.1.6 Radio Button . . . . . . . . . . . . . . . . . . . . . 4 - 13

2.6.3 Setting up Android Studio. . . . . . . . . . . . . 2 - 11 4.1.7 Radio Group . . . . . . . . . . . . . . . . . . . . . . . . 4 - 15

2.6.4 Installing Additional Android 4.1.8 Check Box . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 17


SDK Packages. . . . . . . . . . . . . . . . . . . . . . 2 - 15 4.1.8.1 Check Box Attributes . . . . . . . . . . . 4 - 18

(vii)
(viii)

4.1.9 Progress Bar . . . . . . . . . . . . . . . . . . . . . . . 4 - 19 5.4.3.1 Create a Service . . . . . . . . . . . . . . . . 5 - 27


4.1.9.1 Indeterminate . . . . . . . . . . . . . . . . . . 4 - 19 5.4.4 Service Life Cycle. . . . . . . . . . . . . . . . . . . 5 - 28

4.1.9.2 Result-based. . . . . . . . . . . . . . . . . . . 4 - 20 5.4.5 Permissions . . . . . . . . . . . . . . . . . . . . . . . . 5 - 31


4.2 List View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 21 5.5 Android System Architecture . . . . . . . . . . . . . . . 5 - 31
4.2.1 Grid View . . . . . . . . . . . . . . . . . . . . . . . . 4 - 24 5.5.1 Multimedia Framework. . . . . . . . . . . . . . . 5 - 33
4.2.1.1 Methods of Grid View. . . . . . . . . . . 4 - 25 5.5.2 Play Audio and Video . . . . . . . . . . . . . . . . 5 - 33
4.2.1.2 Android Grid View Attributes. . . . . 4 - 25 5.5.2.1 Playing Audio Files . . . . . . . . . . . . . 5 - 34
4.2.2 Image View . . . . . . . . . . . . . . . . . . . . . . . 4 - 26 5.5.2.2 Playing Video Files . . . . . . . . . . . . . 5 - 34
4.2.3 Scroll View . . . . . . . . . . . . . . . . . . . . . . . 4 - 28 5.5.3 Text to Speech. . . . . . . . . . . . . . . . . . . . . . 5 - 34
4.2.3.1 Vertically Scrolling . . . . . . . . . . . . . 4 - 28 5.5.4 Sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 36
4.2.3.2 Horizontally Scrolling . . . . . . . . . . . 4 - 28 5.5.5 Async Tasks . . . . . . . . . . . . . . . . . . . . . . . 5 - 38
4.2.4 Custom Toast Alert . . . . . . . . . . . . . . . . . 4 - 29 5.6 Audio Capture . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 39
4.2.4.1 Creating a Toast. . . . . . . . . . . . . . . . 4 - 30 5.6.1 Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 39
4.3 Time and Date Picker . . . . . . . . . . . . . . . . . . . 4 - 31 5.7 Bluetooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 41
4.3.1 Date Picker Properties. . . . . . . . . . . . . . . 4 - 31 5.7.1 Animation . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 43
4.3.2 Time Picker Properties . . . . . . . . . . . . . . 4 - 32 5.8 SQLite Database . . . . . . . . . . . . . . . . . . . . . . . 5 - 47
5.8.1 Necessity of SQLite Database. . . . . . . . . . 5 - 48
Unit - V 5.8.2 Creation and Connection of the Database. 5 - 48
5.8.3 Extracting Value from Cursor. . . . . . . . . . 5 - 48
Chapter - 5 Activity and Multimedia with 5.8.4 Transactions . . . . . . . . . . . . . . . . . . . . . . . 5 - 57
Databases (5 - 1) to (5 - 58)
Unit - VI
5.1 Intent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 1
5.1.1 Use of Intent . . . . . . . . . . . . . . . . . . . . . . . . 5 - 1
5.1.2 Types of Intent in Android . . . . . . . . . . . . . 5 - 1 Chapter - 6 Security and Application
Deployment (6 - 1) to (6 - 16)
5.1.3 Intent Filter . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 2
5.1.3.1 Work of Intent . . . . . . . . . . . . . . . . . . 5 - 3 6.1 SMS Telephony . . . . . . . . . . . . . . . . . . . . . . . . 6 - 1
5.2 Activity Life Cycle . . . . . . . . . . . . . . . . . . . . . . 5 - 4 6.1.1 Sending and Receiving SMS Messages . . . 6 - 1
5.2.1 Understanding the Activity Lifecycle . . . . . 5 - 7 6.2 Location Based Service. . . . . . . . . . . . . . . . . . . 6 - 1
6.2.1 Location API's . . . . . . . . . . . . . . . . . . . . . . 6 - 1
5.2.2 Broadcast Life Cycle. . . . . . . . . . . . . . . . . . 5 - 8
6.2.1.1 Classes and Interfaces of Location
5.2.2.1 Types of Broadcasts . . . . . . . . . . . . . . 5 - 8
Based Services. . . . . . . . . . . . . . . . . . 6 - 2
5.3 Content Provider . . . . . . . . . . . . . . . . . . . . . . . 5 - 14 6.2.2 Creating the Project . . . . . . . . . . . . . . . . . . 6 - 2
5.3.1 Creating a Content Provider . . . . . . . . . . . 5 - 16
6.2.2.1 Creating an SMS App . . . . . . . . . . . . 6 - 2
5.3.2 Fragments . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 22 6.2.3 Getting the Maps API Key. . . . . . . . . . . . . 6 - 2
5.3.2.1 Creating a Fragment . . . . . . . . . . . . . 5 - 22 6.2.3.1 What is a Google Maps API Key ? . . 6 - 2
5.3.2.2 Types of Fragments . . . . . . . . . . . . . 5 - 23 6.2.3.2 How to get a Google Maps
5.4 Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 25 API Key ? . . . . . . . . . . . . . . . . . . . . . 6 - 2
5.4.1 Android Services Lifecyle Diagram . . . . . 5 - 26 6.2.4 Displaying the Map . . . . . . . . . . . . . . . . . . 6 - 4
5.4.2 Features of Service . . . . . . . . . . . . . . . . . . 5 - 27 6.2.4.1 Google Map - Layout File . . . . . . . . . 6 - 7
5.4.2.1 Android Platform Service. . . . . . . . . 5 - 27 6.2.4.2 Google Map - Android Manifest File 6 - 7
5.4.3 Defining New Service. . . . . . . . . . . . . . . . 5 - 27
6.2.4.3 Customizing Google Map . . . . . . . . . 6 - 8
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
(ix)

6.2.4.4 Changing Map Type . . . . . . . . . . . . . 6 - 8


6.2.5 Displaying the Zoom Control . . . . . . . . . . 6 - 8
6.2.5.1 Enable/Disable Zoom . . . . . . . . . . . . 6 - 8
6.2.5.2 Important Methods of Zoom
Controls . . . . . . . . . . . . . . . . . . . . . . . 6 - 8
6.2.6 Navigating to Specific Location . . . . . . . . 6 - 8
6.2.6.1 Android Google Map Displaying
Current Location . . . . . . . . . . . . . . . . 6 - 8

6.2.6.2 Callback Methods in Google Map. . . 6 - 9


6.2.7 Adding Markers . . . . . . . . . . . . . . . . . . . . . 6 - 9
6.2.8 Getting Location, Getting Location data,
Monitoring Location . . . . . . . . . . . . . . . . . 6 - 9
6.2.9 Geocoding and Reverse Geocoding. . . . . 6 - 10
6.3 Android Security Model . . . . . . . . . . . . . . . . . 6 - 12
6.3.1 Declaring and using Permissions . . . . . . . 6 - 12
6.3.1.1 Define a Custom App Permission . . 6 - 12
6.3.1.2 App Signing. . . . . . . . . . . . . . . . . . . 6 - 12

6.3.1.3 User IDs and File Access. . . . . . . . . 6 - 13


6.3.1.4 Create a Permission Group . . . . . . . 6 - 13
6.3.2 Using Custom Permission . . . . . . . . . . . . 6 - 13
6.4 Application Deployment. . . . . . . . . . . . . . . . . 6 - 13
6.4.1 Creating Small Application . . . . . . . . . . . 6 - 13
6.4.2 Signing of Application . . . . . . . . . . . . . . . 6 - 13
6.4.2.1 Signing in Debug Mode. . . . . . . . . . 6 - 13
6.4.2.2 Signing in Release Mode. . . . . . . . . 6 - 14
6.4.3 Deploying App on Google Play Store,
Become a Publisher, Developer Console. 6 - 14

Solved Sample Papers (S - 1) to (S - 6)

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
(x)

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - I

1
1.1 Introduction to Android
Android and its Tools

1.1.2 Key Platform Components


Like any technology stack, the Android platform can
1.1.1 What is Android ? be broken down into areas of responsibility to make
· Android is an operating system and programming it easier to understand. The main divisions of the
platform developed by Google for smartphones and Android platform are shown below.
other mobile devices (such as tablets). Applications
· Android is a mobile operating system that is based
on a modified version of Linux with a Java
programming interface.
Application framework
· It was originally developed by a start-up of the
same name, Android, Inc. In 2005, as part of its
strategy to enter the mobile space, Google
Middleware libraries
purchased Android and took over its development
work. Software Development
Kit
· Android was developed by the Open Handset (SDK) and developer tools

Alliance (OHA), which is led by Google. The Open Operating system

Handset Alliance (OHA) is consortium of multiple Fig. 1.1.2 The major components of the Android
companies like Samsung, Sony, Intel and many platform
more to provide a service and deploy handsets The architectural diagram in Fig. 1.1.2 shows that the
using android platform. Android platform can be broken down into five
· Android gives a chance to reuse the application sections :
components and the replacement of native · Applications
applications.
· Application framework
· The most distinguished feature of Android is that it
· Middleware libraries
gives equal opportunities to native apps and third
· Operating system
party apps to use its resources.
· SDK and developer tools
Applications are pretty obvious. But several different
Linux kemel Operating system (Linux kernel)
types of applications are available on most Android
Dalvik virtual machine Middleware
devices and the distinction is subtle. Core open
Native and third Apps (Third party and native apps)
party application source applications are included as part of Android
itself, such as the Browser, Camera, Gallery, Music,
Phone and more. These are typically included with
every Android device. There are also non-open
Fig. 1.1.1 Android environment source Google apps that are included with most
official builds, including Market, Gmail, Maps,
YouTube and more. Many carrier or handset

(1 - 1)® - An up thrust for knowledge


TECHNICAL PUBLICATIONS
Mobile Application Development 1-2 Android and its Tools

manufacturer specific Applications are included on specific builds (such as AT and T's own music
player, Verizon's own Navigator, or Sprint's TV). And, third-party applications are available in the
Android Market, which can be either open source or proprietary. These include independent Google
applications such as Goggles and Listen, official apps from popular services like Twitter and Facebook,
and thousands of other choices.

1.1.3 Android Versions


Google did not attach any high-calorie code name to its initial versions 1.0 and 1.1 of the Android
Operating System. The code names of android ranges from A to N currently, such as Aestro, Blender,
Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat,
Lolipop and Marshmallow. Let's understand the android history in a sequence.

Android Android Android Android Android


1.6 2.0 2.2 2.3 3.0

Donut Eclair Froyo Gingerbread Honeycomb

Android
4.0 Android Android Android Android
4.1 4.4 5.0 6.0
Ice Cream
Sandwich Jelly Bean KitKat Lolipop Marshmallow

Fig. 1.1.3 Android versions

Release Date Version API Level Version Name

September 23, 2008 Android 1.0 1 Apple Pie

February 9, 2009 Android 1.1 2 Banana Bread

April 30, 2009 Android 1.5 3 Cupcake

September 15, 2009 Android 1.6 4 Donut

October 26, 2009 Android 2.0 5 Eclair

December 3, 2009 Android 2.0.1 6

January 12, 2009 Android 2.1 7

May 20, 2010 Android 2.2 8 Froyo

January 18, 2011 Android 2.2.1 8

January 22, 2011 Android 2.2.2 8

November 21, 2011 Android 2.2.3 8


®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-3 Android and its Tools

December 6, 2010 Android 2.3 9 Gingerbread

February 9, 2011 Android 2.3.1 9

July 25, 2011 Android 2.3.3 10

September 2, 2011 Android 2.3.4 10

February 22, 2011 Android 3.0.x 11 Honeycomb

May 10, 2011 Android 3.1.x 12

July 15, 2011 Android 3.2.x 13

October 18,2011 Android 4.0 14 Ice Cream Sandwich

October 19, 2011 Android 4.0.1 14

November 28, 2011 Android 4.0.2 14

December 16, 2011 Android 4.0.3 15

February 4, 2012 Android 4.0.4 15

July 9, 2012 Android 4.1 16 Jelly Bean

July 23, 2012 Android 4.1.1 16

October 9, 2012 Android 4.1.2 16

November 13, 2012 Android 4.2 17

November 27, 2012 Android 4.2.1 17

February 11, 2013 Android 4.2.2 17

July 24, 2013 Android 4.3 18

October 31, 2013 Android 4.4 19 Kitkat

June 23, 2014 Android 4.4.1, 4.4.2, 4.4.3, 4.4.4 19

October 17, 2014 Android 5.0 21 Lollipop

March 09, 2015 Android 5.1 22

October 5, 2015 Android 6.0 23 Marshmallow

December 7, 2015 Android 6.0.1 23

August 22, 2016 Android 7.0 24 Nougat

October 4, 2016 Android 7.1 25

August 21, 2017. Android 8.0 26 Oreo

December 5, 2017 Android 8.1 27 Android Oreo (Go edition)

August 6, 2018 Android 9.0 28 Pie

September 3, 2019 Android 10.0 29 Android Q

1.1.4 Open Handset Alliance (OHA)


· The Open Handset Alliance (OHA) is a consortium whose goal is to develop open standards for
mobile devices, promote innovation in mobile phones and provide a better experience for consumers
at a lower cost.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-4 Android and its Tools

· The Open Handset Alliance is made up of (Audience, Broadcom, Intel, Marvell, NVidia
telecom-related entities, including wireless carriers, Qualcomm, SiRF, Synaptics), software companies
semiconductor companies, handset manufacturers (Ascender, eBay, esmertec, Google, LivingImage,
and software companies. However, several major LiveWire, Nuance, Packet Video, SkyPop,
wireless companies and manufacturers are absent SONiVOX), and commercialization companies
from the coalition, including Nokia, Symbian, (Aplix, Noser, TAT, Wind River). The Alliance
Apple, RIM, Microsoft, Verizon and Cingular. includes the major partners needed to deliver a
· Google and 33 other companies announced the platform for mobile phone applications in all of the
formation of the Open Handset Alliance on major geographies.
November 5, 2007. According to the joint press · The Alliance releases software through Google's
release from that day : developer website (http://developer .android.com).
This alliance shares a common goal of fostering The Android SDK for use by application software
innovation on mobile devices and giving consumers a developers can be downloaded directly from that
far better user experience than much of what is website.
available on today's mobile platforms. · The OHA introduced a mobile device operating
· By providing developers a new level of openness system called Android Symbian operating system.
that enables them to work more collaboratively,
Android will accelerate the pace at which new and 1.1.5 Android Ecosystem
compelling mobile services are made available to Ecosystem in Market terminology refers to the
consumers. inter-dependence between demand and supply.
· For us as mobile application developers, that means In the Android ecosystem this translates to
we are free to develop whatever creative mobile inter-dependence between users, developers and
applications we can think of, free to market them equipment makers. One cannot exist without the
(or give them, at our option) to Android mobile other :
phone owners, and free to profit from that effort · Users buy devices and applications
any way we can. Each member of the Open
· Equipment makers sell devices, sometimes bundled
Handset Alliance has its own reasons for
with applications
participating and contributing its intellectual
property, and we are free to benefit. · Developers buy devices, then make and sell
applications.
· The Open Handset Alliance integrates contributed
software and other intellectual property from its · An open source platform for mobile, embedded and
member companies and makes it available to wearable devices .
developers through the open source community. · Google is the principle maintainer
· Software is licensed through the Apache V2 license, · Other companies contribute to the system.
which you can see at · Each device manufacturer can customize Android to
http://www.apache.org/licenses/LICENSE-2.0.txt. Use suit their needs
of the Apache license is critical, because it allows This new ecosystem is built and developed in order
handset manufacturers to take Android code, to drive the usage of apps. The end-users gain access
modify it as necessary and then either keep it to several mobile apps just because of their
proprietary or release it back to the open source popularity. Thus, the ecosystem of mobile
community, at their option. applications enables the enterprises and the
· The original Alliance members include handset independent developers to develop attractive,
manufacturers (HTC, LG, Motorola, Samsung), feature-rich and unique mobile applications which
mobile operators (China Mobile Communications, will perform rapidly and can essentially garner the
KDDI, DoCoMo, Sprint/Nextel, T-Mobile, Telecom attention of the market.
talia, Telefonica), semiconductor companies
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-5 Android and its Tools

More
devices

OEM's

The Android ecosystem Consumers


More
More
developers
users
and content
App Dev House
Freelancers

Fig. 1.1.4 The Android ecosystem thrives with device compatibility

Android's source code has been used as the basis of 8. Variety


different ecosystems, most notably that of Google 9. Widgets
which is associated with a suite of proprietary
10. Multi-tasking
software called Google Mobile Services (GMS), that
frequently comes pre-installed on the devices. This 11. Google integration
includes core apps such as Gmail, the digital
distribution platform Google Play and associated
Open source
Google Play Services development platform, and
usually apps such as the Google Chrome web
browser. These apps are licensed by manufacturers of Larger developer and
community reach
Android devices certified under standards imposed
by Google. Other competing Android ecosystems
include Amazon.com's Fire OS, or LineageOS. Increased marketing
Software distribution is generally offered through
proprietary application stores like Google Play Store
or Samsung Galaxy Store, or open source platforms Inter app integrator
like Aptoide or F-Droid, which utilize software
packages in the APK format.
Reduced cost of
development
1.1.6 Need of Android
There are many reasons to choose android operating
Higher success ratio
system like

1. Open source
Right development
2. Large developer and community reach environment

3. Increased marketing
1. Reduced cost of development : The development
4. Inter App integration
tools like Android studio, Android SDK, JDK,
5. Reduced cost of development and Eclipse IDE etc. are free to download for the
6. Higher success ratio android mobile application development.
7. Rich development environment
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-6 Android and its Tools

2. Open Source : The Android OS is an 9. Google Integration : Google, the current owners
open-source platform based on the Linux kernel of Android, are highly smart in business.
and multiple open-source libraries. In this way Android devices work seamlessly with all of
developers are free to contribute or extend the Google's products; Google Docs, Gmail, YouTube,
platform as necessary for building mobile apps Google Music, Google Maps, Google Chrome,
which run on Android devices. Google+ etc. Google is regarded as the king of
3. Multi-Platform Support : In market, there are a the web. This is a major attraction for most
wide range of hardware devices powered by the people, as having an android device gives them
Android OS, including many different phones instant access to all of this important software.
and tablet. Even development of android mobile
apps can occur on Windows, Mac OS or Linux. 1.2 Android Features
4. Multi-Carrier Support : World wide a large Android is a powerful open source operating system
number of telecom carriers like Airtel, Vodafone, which provides a lot of great features like :
Idea Cellular, AT and T Mobility, BSNL etc. are · It's an open source and we can customize the OS
supporting Android powered phones. based on our requirements.
5. Open Distribution Model : Android Market · It supports a multi-tasking, we can move from one
place (Google Play store) has very few
task window to another and multiple applications
restrictions on the content or functionality of an
can run simultaneously.
android app. So the developer can distribute
theirs app through Google Play store and as well · It will give a chance to reuse the application
other distribution channels like Amazon's app components and the replacement of native
store. applications.
6. Multi-tasking : Multi-tasking is available on · It has an extensive support for multimedia
virtually all smartphone platforms but hardly hardware control to perform playback or recording
does any operating system do it better than using camera and microphone.
android. Some manufacturers, e.g. Samsung · By using WIFI technology we can pair with other
allows for multi-window tasking. This allows
devices using apps.
users to view multiple apps at the same time.
· It support a connectivity for GSM, CDMA, WIFI,
7. Variety : Android has provided a medium that
NFC, Bluetooth, etc. for telephony or data transfer.
has allowed smartphone manufacturers like
It will allow us to make or receive a calls / SMS
Samsung, HTC, ZTE, Sony and Motorola to allow
messages and we can send or retrieve a data across
their imagination run wild. On Android platform,
there is something for everyone regardless of mobile networks.
taste or budget. Android offers flexibility that is · Android have a multiple APIs to support a
not obtainable with other platforms. location-based services such as GPS.
8. Widgets : Widget is another thing that is · We can perform all data storage related activities by
working absolutely well on Android devices. It using light weight database SQLite.
has worked so excellently, other operating
· It have a wide range of media supports like AVI,
systems and mobile app development are starting
MKV, FLV, MPEG4 etc. to play or record variety of
to adopt something similar, e.g. the Live Tile
audio / video and having a different image formats
System in Windows phone. Widget allows users
like JPEG, PNG, GIF, BMP, MP3, etc.
to access all the necessary information they want
right from the screen, at a glance, without having · It has an integrated open source webkit layout
to launch an app. based web browser to support HTML5, CSS3.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-7 Android and its Tools

· We can access the hardware components like · 2 GB of available disk space minimum, 4 GB
Camera, GPS and Accelerometer. Recommended (500 MB for IDE + 1.5 GB for
· It has a support for 2D/3D Graphics. Android SDK and emulator system image)
· 1280 ´ 800 minimum screen resolution
1.3 Tools and Software Required for
Developing an Android Application Linux
Following are Tools and software required to begin · GNOME or KDE desktop Tested on Ubuntu®
with Android development : 14.04 LTS, Trusty Tahr (64-bit distribution capable
1. Windows (XP or later), Linux (any recent Linux of running 32-bit applications)
distribution) and Mac OS X (10.4.9 or later) · 64-bit distribution capable of running 32-bit
2. Android Studio or Eclipse applications

3. Android SDK · GNU C Library (glibc) 2.19 or later

4. Java · 3 GB RAM minimum, 8 GB RAM recommended;


plus 1 GB for the Android Emulator
System requirements : · 2 GB of available disk space minimum, 4 GB
Recommended (500 MB for IDE + 1.5 GB for
1. Windows/Linux/Mac powered PC
Android SDK and emulator system image)
Operating system is the soul of the PC. So the better
· 1280 ´ 800 minimum screen resolution
your processor is, the easier will be developing
Android over it. There is some basic system · For accelerated emulator : Intel® processor with
requirements which if followed could really ease support for Intel® VT-x, Intel® EM64T (Intel® 64),
Android development . and Execute Disable (XD) Bit functionality, or
Following are the ideal system requirements for AMD processor with support for AMD
developing Android Apps Virtualization™ (AMD-V™)

Recommended Processor
Windows
· Microsoft® Windows® 7/8/10 (32 or 64-bit) More than i3, i5 or i7 developers should be
concerned about the speed of the processor and
· 3 GB RAM minimum, 8 GB RAM recommended;
number of cores. 2 GHz Quad core Intel i3 processor
plus 1 GB for the Android Emulator
would be enough to develop on Android. I have
· 2 GB of available disk space minimum, 4 GB personally used it and did not face any difficulty.
Recommended (500 MB for IDE + 1.5 GB for
Android SDK and emulator system image) 2. IDE (Eclipse or Android Studio)

· 1280 ´ 800 minimum screen resolution Although the SDK can be used to write Android
programs in the command prompt, the most common
· For accelerated emulator : Intel® processor with
method is by using an Integrated Development
support for Intel® VT-x, Intel® EM64T (Intel® 64),
Environment (IDE). Eclipse is quite reputed and
and Execute Disable (XD) Bit functionality trusted IDE. And a lot of people use it for Android
Mac development too. But now a days Android Studio is
preferable, especially for a beginner.
· Mac® OS X® 10.10 (Yosemite) or higher, up to
10.12 (macOS Sierra) Because
· 3 GB RAM minimum, 8 GB RAM recommended; i) Android Studio is a Google product - these are
plus 1 GB for the Android Emulator the same guys who develop Android.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-8 Android and its Tools

ii) Android Studio uses Grade Build system. Which 1) Linux kernel
is quite faster than Eclipse's Apache Ant It is the heart of android architecture that exists at
iii) Android Studio's Autocomplete feature quite the root of android architecture. Linux kernel is
better than that of Eclipse responsible for device drivers, power management,
memory management, device management and
iv) Designing UI has always been complex but
resource access. This layer is the foundation of the
Android Studio has completely changed this.
Android Platform.
v) The new interface design in Android Studio is
faster, responds to changes more rapidly and has Positioned at the bottom of the Android software
more customization options than Eclipse stack, the Linux Kernel provides a level of abstraction
between the device hardware and the upper layers of
3. Android SDK the Android software stack. Based on Linux version
2.6, the kernel provides pre-emptive multitasking,
The Android SDK (software development kit) is a set
low-level core system services such as memory,
of development tools used to develop applications for
process and power management in addition to
Android platform. The Android SDK includes the
providing a network stack and device drivers for
following :
hardware such as the device display, Wi-Fi and
· Required libraries
audio.
· Debugger · Contains all low level drivers for various hardware
· An emulator components support.
· Relevant documentation for the Android · Android Runtime relies on Linux Kernel for core
Application Program Interfaces (APIs) system services like,
· Sample source code · Memory, process management, threading etc.
· Tutorials for the Android OS · Network stack

4. Java · Driver model


· Security and more.
Java Development Kit (JDK) for developing on
Android. 2) Libraries
On top of Linux kernel there is a set of libraries
1.4 Android Architecture
including open-source Web browser engine WebKit,
The Android operating system is built on top of a well known library libc, SQLite database which is a
modified Linux kernel. The software stack contains useful repository for storage and sharing of
Java applications running on top of a virtual application data, libraries to play and record audio
machine. Components of the system are written in and video, SSL libraries responsible for Internet
Java, C, C++, and XML. Android operating system is security etc.
a stack of software components which is roughly
In addition to a set of standard Java development
divided into five sections
libraries (providing support for such general purpose
1) Linux kernel tasks as string handling, networking and file
manipulation), the Android development environment
2) Native libraries (middleware)
also includes the Android Libraries. These are a set of
3) Android runtime Java-based libraries that are specific to Android
development. Examples of libraries in this category
4) Application framework
include the application framework libraries in
5) Applications addition to those that facilitate user interface
building, graphics drawing and database access.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1-9 Android and its Tools

Applications

Home SMS, Media Web


Contacts Dialer Camera player
screen MMS browser

Applications use framework


via API calls
Application framework
Activity Window Content View Notification Package Telephony Resource Location
manager manager providers system manager manager manager manager manager

Application framework is based on runtime

Android Runtime (ART)


Core liabraries Core libraries provide
(Java) Java data structures, etc.

ART/ All android apps run


Dalvik VM via ART/Dalvik VM

Runs stop native (C/C++) libraries

Native libraries (C/C++)


Bionic
Media Surface Audio
libc Webkit SQLite
library framework finger finger

Exposes API to Android from hardware Interacts with kernel

Hardware abstraction layer

Graphics Cellular
Audio Camera Bluetooth GPS Wi-Fi
radio

'Task to' underlying hardware via kernel

Linux kernel Google's kernel enhancement


USB Display Bluetooth Audio Binder Power
Wi-Fi driver
driver driver driver drivers IPC management
+
Camera Keypad Shared More driver
driver driver Mem driver functions

Fig. 1.4.1 Android architecture

A summary of some key core Android libraries · android.database : Used to access data published by
available to the Android developer is as follows : content providers and includes SQLite database
· android.app : Provides access to the application management classes.
model and is the cornerstone of all Android · android.graphics : A low-level 2D graphics drawing
applications. API including colors, points, filters, rectangles and
· android.content : Facilitates content access, canvases.
publishing and messaging between applications and · android.hardware : Presents an API providing
application components. access to hardware such as the accelerometer and
light sensor.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1 - 10 Android and its Tools

· android.opengl : A Java interface to the OpenGL ES C/C++ libraries are included to fulfil a wide and
3D graphics rendering API. diverse range of functions including 2D and 3D
· android.os : Provides applications with access to graphics drawing, Secure Sockets Layer (SSL)
standard operating system services including communication, SQLite database management, audio
messages, system services and inter-process and video playback, bitmap and vector font
communication. rendering, display subsystem and graphic layer
management and an implementation of the standard
· android.media : Provides classes to enable playback
C system library (libc).
of audio and video.
· android.net : A set of APIs providing access to the In practice, the typical Android application developer
network stack. Includes android.net.wifi, which will access these libraries solely through the Java
provides access to the device's wireless stack. based Android core library APIs. In the event that
direct access to these libraries is needed, this can be
· android.print : Includes a set of classes that enable
achieved using the Android Native Development Kit
content to be sent to configured printers from
(NDK), the purpose of which is to call the native
within Android applications.
methods of non-Java or Kotlin programming
· android.provider : A set of convenience classes that
languages (such as C and C++) from within Java code
provide access to standard Android content
using the Java Native Interface (JNI).
provider databases such as those maintained by the
· SQLite Library used for data storage and light in
calendar and contact applications.
terms of mobile memory footprints and task
· android.text' : Used to render and manipulate text execution.
on a device display.
· WebKit Library mainly provides Web Browsing
· android.util : A set of utility classes for performing engine and a lot more related features.
tasks such as string and number conversion, XML
· The surface manager library is responsible for
handling and date and time manipulation.
rendering windows and drawing surfaces of various
· android.view : The fundamental building blocks of apps on the screen.
application user interfaces.
· The media framework library provides media
· android.widget : A rich collection of pre-built user codecs for audio and video.
interface components such as buttons, labels, list
· The OpenGl (Open Graphics Library) and SGL
views, layout managers, radio buttons etc.
(Scalable Graphics Library) are the graphics libraries
· android.webkit : A set of classes intended to allow for 3D and 2D rendering, respectively.
web-browsing capabilities to be built into
· The FreeType Library is used for rendering fonts.
applications.
3) Android runtime
C/C++ Libraries
In android runtime, there are core libraries and DVM
The Android runtime core libraries outlined in the
(Dalvik Virtual Machine) which is responsible to run
preceding section are Java-based and provide the
android application. DVM is like JVM but it is
primary APIs for developers writing Android
optimized for mobile devices. It consumes less
applications. It is important to note, however, that the
memory and provides fast performance. The Dalvik
core libraries do not perform much of the actual
VM makes use of Linux core features like memory
work and are, in fact, essentially Java "wrappers"
management and multi-threading, which is intrinsic
around a set of C/C++ based libraries. When making
in the Java language. The Dalvik VM enables every
calls, for example, to the android.opengl library to
Android application to run in its own process, with
draw 3D graphics on the device display, the library
its own instance of the Dalvik virtual machine.
actually ultimately makes calls to the OpenGL ES C++
library which, in turn, works with the underlying When an Android app is built within Android Studio
Linux kernel to perform the drawing tasks. it is compiled into an intermediate bytecode format

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1 - 11 Android and its Tools

(referred to as DEX format). When the application is 4) Android framework


subsequently loaded onto the device, the Android On the top of Native libraries and android runtime,
Runtime (ART) uses a process referred to as there is android framework. Android framework
Ahead-of-Time (AOT) compilation to translate the includes Android API's such as UI (User Interface),
bytecode down to the native instructions required by telephony, resources, locations, Content Providers
the device processor. This format is known as (data) and package managers. It provides a lot of
Executable and Linkable Format (ELF). classes and interfaces for android application
Each time the application is subsequently launched, development.
the ELF executable version is run, resulting in faster The Application Framework is a set of services that
application performance and improved battery life. collectively form the environment in which Android
This contrasts with the Just-in-Time (JIT) compilation applications run and are managed. This framework
approach used in older Android implementations implements the concept that Android applications are
whereby the bytecode was translated within a Virtual constructed from reusable, interchangeable and
Machine (VM) each time the application was replaceable components. This concept is taken a step
launched. further in that an application is also able to publish
its capabilities along with any corresponding data so
that they can be found and reused by other
Java source
code (.java file) applications.

Java compiler, e.g..javac The Android framework includes the following key
services :
Java bytecode
(.class file) · Activity Manager : Manages the life cycle of an
applications and maintains the back stack as well so
dex translator
that the applications running on different processes
Dalvik executable has smooth navigations.
(.dex file)
· Package Manager : Keeps track of which
interpreted by VM applications are installed in your device.
· Window Manager : Manages windows which are
Dalvik VM
java programming abstractions on top of lower level
surfaces provided by surface manager.
Fig. 1.4.2 Android runtime · Telephony Managers : Manages the API which is
used to build the phone applications
· Dalvik is a specialized virtual machine designed · Content Providers : Provide feature where one
specifically for Android and optimized for application can share the data with another
battery-powered mobile devices with limited application, like phone number, address, etc.
memory and CPU.
· View Manager : Buttons, Edit text, all the building
· Android apps execute on Dalvik VM, a blocks of UI, event dispatching etc.
"clean-room" implementation of JVM
· Resource Manager : Provides access to non-code
· Dalvik optimized for efficient execution embedded resources such as strings, colour settings
· Dalvik: register-based VM, unlike Oracle's and user interface layouts.
stack-based JVM · Notifications Manager : Allows applications to
· Java .class bytecode translated to Dalvik EXecutable display alerts and notifications to the user.
(DEX) bytecode, which Dalvik interprets · Telephony Manager : Provides information to the
application about the telephony services available
on the device such as status and subscriber
information.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 1 - 12 Android and its Tools

· Location Manager : Provides access to the location


services allowing an application to receive updates
about location changes

5) Applications
On the top of android framework, there are
applications. These comprise both the native
applications provided with the particular Android
implementation (for example web browser and email
applications) and the third party applications installed
by the user after purchasing the device. 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 Linux


kernel. Any applications that you write are located at
this layer.

qqq

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - II

2
2.1 The Android Operating System
Installation and
Configuration of Android

· Android is an open-source mobile operating system. It is a variant of Linux hence providing extensive
security, modularity and productivity at the mobile device level.
· Originally, Android was created by a company called Android Inc. Google acquired this company in
2005. After then, Google made it open source.
· Android has seven major releases each having several minor revisions. In order to follow these
versions easier, developers name them with cookie names. The popular versions of Android are Kitkat
(Android 4.4), Lollipop (Android 5.1) and Marshmallow (Android 6.0), Nougat (Android 7.0) is also
gaining popularity.
· Android is utilized not only in smartphones but also in tablets, netbooks, digital television boxes,
handheld game devices and even in single board computers such as UDOO. UDOO is a single-board
computer with an integrated Arduino Due compatible microcontroller, designed for computer science
education, the world of Makers and the Internet of Things.

2.1.1 How do Android Apps Work ?

Our project
Android
What
Java code APK Dalvik virtual the
Graphics DFX code machine user
Sound + resources sees
Layouts
Other resources

Linux, specialist libraries and


manufacturer's drives

API's Hardware (CPJ, Graphics card, GPS,


camera, Sensors, etc... )

Fig. 2.1.1 Working of Android Apps

· There are different ways the programs run on various platforms. The lowest level software can be
written in machine code that runs directly on the microprocessor. This is shown in Fig. 2.1.2. Since it
is difficult to develop complex applications in machine code, operating systems are used. Operating
systems provide a communication and control layer between the application software and the
hardware as shown in Fig. 2.1.3. If we want to develop a native application for running on a specific

(2 - 1)
Mobile Application Development 2-2 Installation and Configuration of Android

hardware / operating system, we have to do


this using a compiler and linker. Compiler and
linker takes the source code and creates the Machine
code
executable file that actually runs on the
Hardware
operating system as shown in Fig. 2.1.4. For
example, if we want to develop an application
in C++ programming language, we have to Fig. 2.1.2 Machine code - hardware relation
utilize the compilation/linking process.
· The main advantage of native applications is
their speed. However, the disadvantage is the
incompatibility across different platforms. For
example, we cannot run a native Windows Application
software
application on Ubuntu and vice versa. Virtual
Operating
machine concept is developed to overcome this systen
limitation. Virtual machine is software that runs
Hardware
on the operating system and provides an
abstraction to the developer as shown in
Fig. 2.1.3 Operating system layer
Fig. 2.1.5. The application software runs on top between the hardware and the app
of the virtual machine.

Executable
Source Computer file - runs on the
Linker
code operating system

Fig 2.1.4 Creating a native executable from the source code

· Therefore, as long as a computer has the virtual machine running, the application software can run on
that computer independent of the hardware and the
operating system. A good example is the Java Virtual
Machine (JVM). JVM runs on almost all operating
Application
systems and platforms. Therefore, when we develop software
Java software, it will be run on the JVM independent Virtual
of the operating system/platform. The obvious machine
advantage of developing apps that run on virtual Operating
system
machines can then be stated as : "develop once and
run on all platforms". However, applications running Hardware
on virtual machines are slower than native
applications. General development process of virtual Fig. 2.1.5 Virtual machine between the app
machine applications is summarized in Fig. 2.1.6. and the operating system

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-3 Installation and Configuration of Android

Source Intermediate Virtual


Compiler
code output machine

Interpreted as
native code

Fig 2.1.6 Creating an intermediate code from the source code -


intermediate code is interpreted by the virtual machine

· Similar to Java applications, Android applications also run on a JVM. There are two special virtual
machines used in Android : Dalvik Virtual Machine (DVM) and Android RunTime (ART). These are
specialized JVMs which can run on low system resources. The .apk files (executables of Android apps)
actually run on these virtual machines. DVM has been the default runtime environment (~ virtual
machine) until the Lollipop release (Android 5.0). ART is introduced by Android 4.0 and has been the
default VM as of Android 5.0. DVM and ART basically do the same job : running Android apps
independent of the platform. The main advantage of ART over DVM is the utilization of a concept
called Ahead of Time (AOT) compilation instead of Just in Time (JIT) approach. In AOT, apps are
compiled during installation hence they load faster with lower CPU usage. On the other hand, JIT
compilation provides lower storage space consumption with relatively longer loading times.

2.1.2 Java Development Kit (JDK)


· The Android SDK was developed using the Java programming language. Similarly, Android
applications are also developed using Java. As a result, the Java Development Kit (JDK) is the first
component that must be installed. Android development requires the installation of version 7 or
above of the Standard Edition of the Java Platform Development Kit. Java is provided in both
development (JDK) and runtime (JRE) packages.

How Java and Android work together ?


· After writing a program in Java for Android, we click on a button to change our code into another
form that is understood by Android. This other form
is called Dalvik EXecutable (DEX) code, and the Java applications
transformation process is called compiling.
Java API
· Compiling takes place on the development machine Activity, View, Graphics, Widget, OpenGL,
Telephony, Media, Speech, Net, Webkit, Content,
after we click on that button. Database, Animation, Bluetooth, Location, JUnit,
Apache HTTP, JSON, DOM, SAX, XMLPull
· The part of the Android system that executes (runs) Core JDK (exclude AWT/Swing)
our compiled DEX code is called the Dalvik Virtual
Dalvik Java Virtual Machine (DVM)
Machine (DVM). The DVM itself is a piece of
software written in another language that runs on a Media, Graphics, OpenGL, FreeType, SQLite, Webkit
specially adapted version of the Linux operating Native C/C++ libraries

system. So what the user sees of Android, is itself


Device drivers
just an app running on another operating system. Linux kernel

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-4 Installation and Configuration of Android

· The purpose of the DVM is to hide the complexity and diversity of the hardware and software that
Android runs on but, at the same time, its purpose is to expose all of its useful features. This
exposing of features generally works in two ways. The DVM itself must have access to the hardware,
which it does, but this access must be programmer friendly and easy to use. The way the DVM
allows us access is indeed easy to use because of the Android Application Programming Interface
(API).

2.1.3 Android SDK

SDK platform Documentation


There's one of these for each So you can access the latest
version of android. API documentation offline.

SDK tools
Tools for debugging and testing, Android support
plus other useful utilities. The Extra APIs that aren't available
SDK also features a set of in the standard platform.
platform dependent tools

Google play billing


Sample apps Allows you to integrate billing
If you want practical code services in your app.
examples to help you understand
how to use some of the APIs, the
sample apps might help you.

Fig. 2.1.7 Android SDK

· The Android SDK is a software development kit for Android development that contains the necessary
components to build Android applications. It comes as part of the Android Studio and includes a
comprehensive set of development tools including a debugger, software libraries of prewritten code, a
device emulator to run your Android applications, documentation, sample code, and tutorials. These
tools are used to create apps that look great and take advantage of the hardware capabilities.
· The Android Virtual Device manager that comes with the Android SDK enables to test application
with any version of Android.
· The Android SDK and Gradle tooling incorporate the needed tools to build, compile, and package
Android applications.
· For debugging Android applications, the Android Debug Bridge (adb) tool that enables to connect to
any virtual or real Android device.
· Here's the list of the important packages in the Android SDK :
· SDK Tools · SDK Platform Tools · SDK Platform · System Image · SDK Samples

2.2 Android - Developer Tools


· The android developer tools are used to create interactive and powerful application for android
platform. The tools can be generally categorized into two types.
· SDK tools · Platform tools

SDK tools :
SDK tools are generally platform independent and are required no matter which android platform you
are working on. When you install the Android SDK into your system, these tools get automatically
installed. The list of SDK tools has been given below -
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-5 Installation and Configuration of Android

Sr. No. Tool and description range of different devices. Additional templates
may be loaded or custom configurations created to
1. android
This tool lets you manage AVDs, projects, and match any physical Android device by specifying
the installed components of the SDK properties such as processor type, memory capacity
2. ddms and the size and pixel density of the screen. When
This tool lets you debug Android applications launched, an AVD will appear as a window
3. Draw 9-Patch containing an emulated Android device
This tool allows you to easily create a environment. Fig. 2.3.1, for example, shows an AVD
NinePatch graphic using a WYSIWYG editor
session configured to emulate the Google Nexus 6
4. emulator API 15 model. New AVDs are created and managed
This tools let you test your applications using the Android Virtual Device Manager, which
without using a physical device
may be used either in command-line mode or with a
5. mksdcard
more user-friendly graphical user interface.
Helps you create a disk image (external sdcard
storage) that you can use with the emulator

6. proguard
Shrinks, optimizes, and obfuscates your code
by removing unused code

7. sqlite3
Lets you access the SQLite data files created
and used by Android applications

8. traceview
Provides a graphical viewer for execution logs
saved by your application

9. Adb
Android Debug Bridge (adb) is a versatile
command line tool that lets you communicate
with an emulator instance or connected
Android-powered device.

2.3 Android Virtual Device (AVD)

An Android Virtual Device (AVD) is an emulator


configuration that allows developers to test the
application by simulating the real device capabilities,
without the necessity to install the application on a
physical Android based device. An AVD may be
configured to emulate a variety of hardware Fig. 2.3.1 Sample AVD
features including options such as screen size,
memory capacity and the presence or otherwise of An AVD contains a hardware profile, system image,
features such as a camera, GPS navigation support or storage area, skin, and other properties.
an accelerometer. As part of the standard Android
Studio installation, a number of emulator templates
are installed allowing AVDs to be configured for a

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-6 Installation and Configuration of Android

AVD and app features :

Hardware Profile Property Description

Device Name Name of the hardware profile. The name can contain uppercase or lowercase letters, numbers
from 0 to 9, periods (.), underscores (_), parentheses ( () ), and spaces. The name of the file
storing the hardware profile is derived from the hardware profile name.

Device Type Select one of the following :


Phone/Tablet
Wear OS
Android TV
Chrome OS Device
Android Automotive

Screen Size The physical size of the screen, in inches, measured at the diagonal. If the size is larger than
your computer screen, it's reduced in size at launch.

Screen Resolution Type a width and height in pixels to specify the total number of pixels on the simulated
screen.

Round Select this option if the device has a round screen, such as some Wear OS devices.

Memory : RAM Type a RAM size for the device and select the units, one of B (byte), kB (kilobyte),
MB (megabyte), GB (gigabyte) or TB (terabyte).

Input : Has Hardware Select this option if your device has hardware navigation buttons. Deselect it if these buttons
Buttons (Back/Home/Menu) are implemented in software only. If you select this option, the buttons won't appear on the
screen. You can use the emulator side panel to "press" the buttons, in either case.

Input: Has Hardware Select this option if your device has a hardware keyboard. Deselect it if it doesn't. If you select
Keyboard this option, a keyboard won't appear on the screen. You can use your computer keyboard to
send keystrokes to the emulator, in either case.

Navigation Style Select one of the following :


None - No hardware controls. Navigation is through the software.
D-pad - Directional Pad support.
Trackball
Wheel
These options are for actual hardware controls on the device itself. However, the events sent
to the device by an external controller are the same.

Supported Device States Select one or both options :


Portrait - Oriented taller than wide.
Landscape - Oriented wider than tall.
If you select both, you can switch between orientations in the emulator. You must select at
least one option to continue.

Cameras To enable the camera, select one or both options :


Back-Facing Camera - The lens faces away from the user.
Front-Facing Camera - The lens faces toward the user.
Later, you can use a webcam or a photo provided by the emulator to simulate taking a photo
with the camera.

Sensors : Accelerometer Select if the device has hardware that helps the device determine its orientation.

Sensors: Gyroscope Select if the device has hardware that detects rotation or twist. In combination with an
accelerometer, it can provide smoother orientation detection and support a six-axis orientation
system.

Sensors : GPS Select if the device has hardware that supports the Global Positioning System (GPS)
satellite-based navigation system.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-7 Installation and Configuration of Android

Sensors: Proximity Sensor Select if the device has hardware that detects if the device is close to your face during a phone
call to disable input from the screen.

Default Skin Select a skin that controls what the device looks like when displayed in the emulator.
Remember that specifying a screen size that's too big for the resolution can mean that the
screen is cut off, so you can't see the whole screen.

2.4 Android Emulator


Android Emulator is used to run, debug and test the android application. If you don't have the real
device, it can be the best way to run, debug and test the application.

An emulator is an application that supports a virtual device which prototypes, develops and tests the
applications without using a real device. It acts as all hardware and software features of device. It
cannot make a real phone call. It runs a full Android system stack, down to the kernel level. It includes
a set of preinstalled applications (such as the dialer, messenger) which can be accessed from our
applications.

Each AVD is an independent device. It has its own storage and data. In each configuration, an
Android platform is specified which is to be run in the emulator along with the set of hardware
options, emulator skin, etc. when emulator is launched, we specify the AVD configuration that we
want to load. As soon as we launch the emulator with an AVD configuration, it automatically loads the
user data and SD card data from the AVD directory. By default, cache, user data and SD card is stored
in AVD directory. AVD manager manages all the emulators.

Emulator 1 Emulator 2 Emulator n

AVD AVD AVD


configuration 1 configuration 2 configuration n

Android virtual device


manager

Fig. 2.4.1 Relation between AVD Manager, AVD and Emulator

2.5 Dalvik Virtual Machine (DVM)


The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It
optimizes the virtual machine for memory, battery life and performance.

Dalvik is a purpose built virtual machine designed specifically for android which was developed by
Dan Bornstein and his team. Strictly it was developed for mobile devices. Dalvik virtual machine uses
register based architecture. With this architecture dalvik virtual machine has few advantages over JAVA
virtual machine such as :

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-8 Installation and Configuration of Android

1. Dalvik uses its own 16 bit instruction set than Key Feature :
java 8 bit stack instructions, which reduce the · Android dalvik virtual machine is a registered
dalvik instruction count and raised its interpreter based Virtual machine.
speed. · With using DVM, android device can run multiple
2. Dalvik use less space, which means an instances of VM efficiently.
uncompressed .dex file is smaller in size(few · Duplicate String and other constants used in
bytes) than compressed java archive file(.jar file).
multiple class files are included only once in the
The Dex compiler converts the class files into the
.dex Output to conserve space.
.dex file that run on the Dalvik VM. Multiple
· Java byte code is also converted into alternative
class files are converted into one dex file.
instruction set used by DVM.
The compiling and packaging process : · An uncompressed .dex file is smaller in size as
compare to compressed .jar derived from same
.java files .class file.
.dex file
Source Code · The Dalvik executable may be modified again when
installed onto the mobile devices.
r · DVM was slimmed down to use less space.
ile
p
m
Java compiler
x co x) Packaging · The Dalvik VM executes file in Dalvik executable
(javac) e ( d (aapt)
D (.dex) format which is optimized for minimal
memory foot print.
· DVM not only can run multiple VM instances but
.class files .apk file creation of new VM must be fast as well.
Comparison of Java VM and the Dalvik virtual
machine :
Fig. 2.5.1 Compiling and packaging process

Sr. DVM (Dalvik Virtual JVM (Java Virtual


· As shown in Fig. 2.5.1, the javac tool compiles the No. Machine) Machine)
java source file into the class file.
· The dx tool takes all the class files of your 1. It is Register based which It is Stack based.
is designed to run on low
application and generates a single .dex file. It is a memory.
platform-specific tool.
· The Android Assets Packaging Tool (aapt) handles 2. DVM uses its own byte JVM uses java byte code
code and runs ".Dex" file. and runs ".class" file
the packaging process. From Android 2.2 SDK having JIT (Just In Time).
Dalvik has got a Just in
Role of Dalvik Virtual Machine : Time compiler
In java we write and compile java program using
3. DVM has been designed Single instance of JVM is
java compiler and run that bytecode on the java so that a device can run shared with multiple
virtual machine. On the other side, In android we multiple instances of the applications.
VM efficiently.
still write and compile java source file (bytecode) on Applications are given
java compiler, but at that point we recompile it once their own instance.
again using dalvik compiler to dalvik bytecode (dx 4. DVM supports Android JVM supports multiple
tool converts java .class file into .dex format) and this operating system only. operating systems.
dalvik bytecode is then executed on the dalvik virtual
5. For DVM very few For JVM many Re-tools
machine.In android Architecture there is DVM above Re-tools are available. are available.
Linux kernel.
6. There is constant pool for It has constant pool for
Every single application runs as one process and every application. every class.
every process has its own instance of DVM. Every
7. Here the executable is Here the executable is
time user click on app icon then above process will APK. JAR.
execute.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2-9 Installation and Configuration of Android

Java Source
code Java Source
(.java) code
Java (.java)
compiler Java
(javac) compiler
(javac)
Java Byte code
(.class) Java Byte code
(.class)
DEX
compiler

Dalvik Byte
code
(.dex)

Register-based Register-based

Java Virtual
Dalvik Virtual Machine
Machine (JVM)
(DVM)

Windows JDK Installation :


2.6 Steps to Install and Configure
Android Studio and SDK For Windows systems, the JDK may be obtained from
Oracle Corporation's website using the following
2.6.1 The development environment URL : http://www.oracle.com/technetwork/java/javase/downl
A development environment is a term that refers to oads/jdk8-downloads-2133151.html
having everything you need in order to develop, set 1. Assuming that a suitable JDK is not already
up, and be ready to go in one place. installed on your system, download version 8 of
the JDK package that matches the destination
Android Studio is an integrated development computer system. Once downloaded, launch the
environment (IDE) that takes care of all the installation executable and follow the on screen
complexities of compiling our code and linking with instructions to complete the installation process.
the JDK and the Android API. Once we have 2. There will be a series of windows that will guide
installed the JDK and Android Studio, we can do us through the installation process. The most we
everything we need inside this application. have to do is just click on Next to proceed. The
following is a screenshot of the first window that
2.6.2 Installing the Java Development Kit (JDK) you will see during the installation :
The Android SDK was developed using the Java
programming language. Similarly, Android
applications are also developed using Java. As a
result, the Java Development Kit (JDK) is the first
component that must be installed.

Android Studio development requires the installation


of version 8 of the Standard Edition of the Java
Platform Development Kit. Java is provided in both
development (JDK) and runtime (JRE) packages. For
the purposes of Android development, the JDK must
be installed.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 10 Installation and Configuration of Android

3. Now, click on Next and you will see this window :

4. click on the Change button and you will see this window :

5. Browse to the hard drive where you will be installing all of your development tools. Then simplify
the names of the folders in which you will install the JDK to just Java\JDK\.
Folder name :
D:\Java\JDK

6. After choosing installation location and folder names, click on Next.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 11 Installation and Configuration of Android

7. Click on Next. 12. As shown in the above screenshot, type


8. Next, you will see the window that says 3 Billion JAVA_HOME in Variable name and enter
Devices Run Java. D:\Java\JDK in the Variable value field. If
you've installed the JDK somewhere else, then
the file path you enter in the Variable value field
will need to point to where you've placed it. Be
sure to type it correctly, make sure that the
slashes \ are the right way around, and don't
add any extra slashes.

13. Click on OK to save your new settings. Now,


click on OK again to clear the Advanced system
settings window.

2.6.3 Setting up Android Studio


1. Visit https://developer.android.com/sdk/index.html
9. Now, you will see the final screen. and click on the Download Android Studio for
Windows button. If at the time of reading this
the link has changed, simply Google Download
Android Studio.
2. Next, you will see the Terms and Conditions
page as shown in the following screenshot :

10. Click on Close, and we are almost done


installing the JDK.
11. Now, we will make sure that Windows (and all
its applications) know where to find the JDK.
Right-click on your My Computer icon and
Properties | Advanced system settings |
Environment Variables | New (under System
variables and not under User variables). Now
you can see the New System Variable dialog as 3. Click on the "I have read and agree with the
follows : above terms and conditions" checkbox as
highlighted in the above screenshot.
4. Now, click on the DOWNLOAD ANDROID
STUDIO FOR WINDOWS button. Wait for the
download to complete.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 12 Installation and Configuration of Android

5. Open the folder where you have downloaded Android Studio. Right-click on the
android-studio-bundle-141.1980579 -windows.exe file and select Run as administrator. Your file will
most likely have a different name based on whichever is the current version of Android Studio at
the time.

6. When you get the Do you want the following program to be allowed to make changes to this
computer message, click on Yes. You will see the first window of the installation process.

7. Let's step through the setup process a window at a time. Pictured next is the first window that you
will see when you start the setup process :

8. Click on Next. Now we can see a few options, as in this next screenshot :

9. Make sure that all the options have a tick next to them, and then click on Next.
10. The next window is the license agreement. Click on "I Agree". Take a look at the next screenshot
that shows you the Install Locations window :

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 13 Installation and Configuration of Android

11. In this step, we want to install the Android Studio IDE and Android SDK to the same hard drive
where we installed the JDK. So you might just be able to click on Next at this point. However, if
you've installed the JDK to another drive, then we need to change the drive and the folders we use
at this step too. This isn't strictly essential, but it can avoid problems for some users.
12. For Android Studio Installation Location, choose the root of the drive where you've installed the
JDK followed by \Android Studio. So in my case, this will be D:\Android Studio. For Android
SDK Installation Location, choose the same hard drive and simply add Android\sdk as the
location. So if, like me, you've installed the JDK on D:, then choose D:\Android\sdk. The next
screenshot makes this clear :

13. Click on Next when you have selected your installation locations.
14. Next, you might see the Emulator Setup window as pictured in the next figure. If you do, then
accept the default settings and click on Next; otherwise, you can skip to step 15. Don't worry if you
don't see this screen, it is a minor issue to do with running the Android emulators a bit more
smoothly. Most of the time, you will probably want to use a real device anyway.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 14 Installation and Configuration of Android

15. The next window asks you to choose a start menu folder, just as when we install any new
Windows app. You might want to make a note of this location. Click on Install to accept the
default settings, and Android Studio will begin to install itself and extract the SDK to the
appropriate folder that we selected earlier. This might take some time.
16. When you see the Installation Complete window, click on Next. Now, you will see the following
window :

17. Click on Finish to bring up the second to last window of the installation process. Assuming that
this is your first time using Android Studio, click on the "I do not have a previous version of
Android Studio" or "I do not want to import my settings" radio button and click on OK.

18. Now, in the next screenshot, you get to choose the theme that Android Studio will use. If you like
conventional black texts on white background appearance, then choose IntelliJ, and if you want a

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 15 Installation and Configuration of Android

cool dark style, choose Darcula. You can alter any of these schemes from within Android Studio if
you change your mind later.

19. Click on Next when you have chosen your theme.


20. Now Android Studio will connect to the Internet and download some of the Android tools that we
will be using soon. Again, this could take a while.
21. When the Downloading Components window has done its work, it will present you with a Finish
button, Click on it.
22. Finally, we are presented with the Welcome to Android Studio screen. This screen, among other
things, allows us to start a new project or open an existing project. Take a look at the next
screenshot :

2.6.4 Installing Additional Android SDK Packages


The steps performed so far have installed Java, the Android Studio IDE and the current set of default
Android SDK packages. Before proceeding, it is worth taking some time to verify which packages are
installed and to install any missing or updated packages.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 16 Installation and Configuration of Android

This task can be performed using the Android SDK Settings screen, which may be launched from
within the Android Studio tool by selecting the Configure -> SDK Manager Option from within the
Android Studio welcome dialog. Once invoked, the Android SDK screen of the default settings dialog
will appear as shown below :

Immediately after installing Android Studio for the first time it is likely that only the latest released
version of the Android SDK has been installed. To install preview or older versions of the Android
SDK simply select the checkboxes corresponding to the versions and click on the Apply button.
It is also possible that updates will be listed as being available for the latest SDK. To access detailed
information about the packages that are available for update, enable the Show Package Details option
located in the lower right hand corner of the screen. This will display information similar to that
shown in Figure.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 17 Installation and Configuration of Android

The above figure highlights the availability of an update. To install the updates, enable the checkbox to
the left of the item name and click on the Apply button.

In addition to the Android SDK packages, a number of tools are also installed for building Android
applications. To view the currently installed packages and check for updates, remain within the SDK
settings screen and select the SDK Tools tab as shown below :

Setting up an Android Studio Development Environment

Within the Android SDK Tools screen, make sure that the following packages are listed as Installed in
the Status column :
· Android SDK Build-tools

· Android SDK Tools

· Android SDK Platform-tools

· Android Support Repository

· Android Support Library

· Google Repository

· Google USB Driver (Windows only)

· Intel x86 Emulator Accelerator (HAXM installer)


In the event that any of the above packages are listed as Not Installed or requiring an update, simply
select the checkboxes next to those packages and click on the Apply button to initiate the installation
process.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 18 Installation and Configuration of Android

Once the installation is complete, review the package list and make sure that the selected packages are
now listed as Installed in the Status column. If any are listed as Not installed, make sure they are
selected and click on the Install packages… button again.

An alternative to using the Android SDK settings panel is to access the Standalone SDK Manager
which can be launched using the link in the lower left hand corner of the settings screen. The
Standalone SDK Manager provides a similar list of packages together with options to perform update
and installation tasks :

2.6.5 Installation of Emulators

Emulators are software that mimics the behaviour of real devices. When we develop an app, we
obviously won't have all the possible devices (Android phones, tablets, etc.) available at hand. Because
of this, we run the apps on emulators for testing on various devices. Emulators are also called as
"Android Virtual Devices (AVDs)" in Android Studio. When Android Studio is first installed, there is
no default AVD. We need to create one before testing our apps.

1. For this, select Tools ® Android ® AVD Manager as shown below :

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 19 Installation and Configuration of Android

2. When AVD Manager appears, there won't be any AVDs created or installed. Please click on the
Create a Virtual Device button as shown below :

3. AVD Manager will show a detailed window.

4. You can select various devices with different screen sizes and other hardware properties. You can
select device groups from the left pane as TV, Phone, etc. Phone group is the default selection. In
this group, Nexus 5 is also selected by default. When you click "Next", you'll be presented by
choices for the Android version of the AVD as shown below.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 2 - 20 Installation and Configuration of Android

5. The recommended targets start from Android 5.1. We can Android 7.0 with Goole APIs (Nougat)
as shown in the figure. Then, please click "Next" and give a name you like to the AVD.

6. After clicking "Finish", the AVD is created and shown in the AVD Manager as

7. You can now try your Android apps on this AVD, which will accurately mimic the behaviour of a
real Nexus 5 phone. We can run the AVD by clicking the "Play" button shown inside the square in
above Figure
8. The virtual device will appear as in Figure below which you can use like a real Nexus 5 phone.

qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - III

3
3.1 The Development Process
Components and Layouts

An Android app project begins with an idea and a definition of the requirements necessary to realize
that idea. As the project progresses, it goes through design, development, and testing.

Defining the ideas and requirements Resources in XML


Prototyping the user interface Components and tests in Java
Developing and testing the app Manifests
Publishing the app Build configurations

Your app

Fig. 3.1.1 The development process


The above diagram is a high-level picture of the development process, with the following steps :
1. Defining the idea and its requirements : Most apps start with an idea of what it should
do,bolstered by market and user research. During this stage the app's requirements are defined.
2. Prototyping the user interface : Use drawings, mock ups and prototypes to show what the user
interface would look like, and how it would work.
3. Developing and testing the app : An app consists of one or more activities. For each activity you
can use Android Studio to do the following, in no particular order:
· Create the layout : Place UI elements on the screen in a layout, and assign string resources and
menu items, using the Extensible Markup Language(XML).
· Write the Java code : Create source code for components and tests, and use testing and
debugging tools.
· Register the activity : Declare the activity in the manifest file.
· Define the build : Use the default build configuration or create custom builds for different
versions of your app.
· Publishing the app : Assemble the final APK (package file) and distribute it through channels
such as the Google Play.
General steps of app development for developing our first app :

1. Creating an Android Studio project.


2. Setting up the User Interface (UI) of the app.
3. Connecting the UI components such as buttons, textboxes, etc. to the Java code.
4. Coding in Java - the actual programming part.

(3 - 1)
Mobile Application Development 3-2 Components and Layouts

5. Building the project : This means creating the executable (file that actually runs on device or the
emulator). This is not difficult as it sounds; Android Studio does the entire job with a single click
6. Trying the app on an emulator.
7. Running the app on a real Android device (optional).
8. Publishing the app on Google Play (optional).

3.1.1 Creating the Project


1. Start Android Studio by clicking on its icon in the start menu.
2. If you get the Windows Firewall has blocked some features of this program message, as pictured
in the next screenshot, click on Allow access :

3. Now, you will see the Welcome to Android Studio start menu ,click on Start a new Android
Studio project. You will see the New Project screen pictured next.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-3 Components and Layouts

4. First, give name to application in the Application name field.


You can choose any name you like for your first application, but just be aware that Android
Studio will soon generate a whole bunch of code and files for us and that the name you choose
will be reflected in them. If you want your code and files to be identical to those that we will be
examining shortly, call your application Hello Android.
5. Next, the Company Domain field. This is where you will enter the details of your company. It is
a convention and very practical (because it is unique) to use the domain name of your company
website. Unlike the application name, using a different company domain will have almost zero
effect on the code and files. Choose and enter a company domain name.
6. Now, the Package name field. It has been automatically derived from the previous two fields.
Remember that a package is a collection of the Java classes that are our code files, and our apps
can comprise one or more packages if we wish them to, but they must comprise at least one
package. We can edit the package name by clicking on the edit link, but we have no need to do so
here.
7. Finally, in the Project location field, you can accept the default settings or browse to the location
where you would like to store all your Android projects. You have the option to change this for
each project that you create.

8. Click on the Next button to continue and you will see the Target Android Devices window:

9. Here, we can see that we have the option of developing an application for a phone, tablet, TV, and
wear. Wear is the range of Android-enabled smartwatches. In the preceding screenshot, in the
grayed-out part at the bottom of the window, we can also see that we can develop for Glass,
Google's trendy Android-enabled glasses, although we would need to install additional files to do
this. In this book, we will be developing for phones and tablets, so the already selected option is
just what we need. The only other thing we need to choose on this screen is the Minimum SDK.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-4 Components and Layouts

We already know that the Android SDK is a collection of packages of code that we will be using to
develop our apps. Like any good SDK, the Android SDK is regularly updated, and each time it
gets a significant update, the version number is increased. Simply put, the higher the version
number, the newer the features you get to use; the lower the version number, the more devices
our app will work on. For now, the default setting API 15: Android 4.0.3 (IceCreamSandwich) will
give us lots of great features and at least 90% compatibility with the Android devices that are
currently in use.
10. Click on the Next button. Now we can see the Add an activity to Mobile window :

11. An Activity class is a special Java class and every Android app must have at least one. It is the
part of the code where our app will start when it is launched by the user, and this also handles
any interaction with the user. The options on this screen provide different ready-made templates of
the Activity class code in order to give programmers a fast start when creating various types of
apps. As we are starting from scratch, the most appropriate option for us is Blank Activity. Make
sure that Blank Activity is selected by clicking on it and then clicking on Next. Now, take a look at
the Customize the Activity window :

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-5 Components and Layouts

12. The Customize the Activity window gives us four things. It is perfectly possible to leave them all
at their default settings. Activity Name is the name of the class that will contain our code. Name
the activity MyActivity.
13. The next field is Layout Name. Android UI layouts are usually defined in a separate XML text file,
not with our Java code. The layout name is what this file will be called. Name the layout
my_layout.
14. The next field is Title. This is different than the Activity Name field and will be used by Android
on the device's screen as the name of the app. Name the title My App.
15. Finally the Menu Resource Name. Menus are the pop-up options that you get on Android when
you click on the menu button. They might also be shown on the topmost bar of the app known as
the action bar. This varies depending on the version of Android a device is running. These are
considered to be part of the UI as well and are usually defined in this separate XML file. Name the
menu file my_menu.
16. Click on the Finish button, and Android Studio will now create a project for us based on our
choices.
Lets get familier with the main sections of Android Studio

1. Main Sections of the IDE : Android Studio is a sophisticated tool and it has dozens of properties
to make app development easier. The main sections of Android Studio is as shown in Figure 3.1.2

Fig. 3.1.2 Basics sections of Android Studio

Section 1. The project files and folders can be viewed from here. In addition, new files can be added
from this pane. We need to double-click on the filenames here to open them in the middle pane. The
project structure will be explained in detail in the next subsection.

Section 2. The opened files can be activated from the tabs located here for viewing in the middle pane

Section 3. This is the middle pane. Contents of the active files can be viewed and changed from here.
For the project shown in Figure 3.1.2, the file called "MainActivity.java" is the active tab in Section 2
therefore the middle pane in Section 3 shows the contents of this "MainActivity.java" file.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-6 Components and Layouts

Section 4. This section is also controlled via tabs. The developer can switch project files, structures,
captures and favourites for viewing in the left pane.

Section 5. The current or previous compilation, building or debugging processes are shown here. For
the snapshot of Figure 3.1.2, it is indicated that the "Gradle build finished in 14 seconds". Gradle is the
build system of Android Studio. Therefore, the message says that the building engine completed its
previous task in 14 seconds.

Section 6. This is the Run button of Android Studio. When we set up the user interface and write the
Java code of a project, we click this button to make the Android Studio build the project (which means
creating the executable file from project files) and then we can run it on an emulator or on a real
device.

2. The Tool Windows : In addition to the project view tool window, Android Studio also includes a
number of other windows which, when enabled, are displayed along the bottom and sides of the
main window. The tool window quick access menu can be accessed by hovering the mouse
pointer over the button located in the far left hand corner of the status bar (Fig.3.1.3) without
clicking the mouse button(pointed by the arrow).

Fig. 3.1.3 The Tool Window of Android Studio

Selecting an item from the quick access menu will cause the corresponding tool window to appear
within the main window. Alternatively, a set of tool window bars can be displayed by clicking on the
quick access menu icon in the status bar. These bars appear along the left, right and bottom edges of
the main window (as indicated by the arrows in Fig 3.1.4) and contain buttons for showing and hiding
each of the tool windows. When the tool window bars are displayed,a second click on the button in the
status bar will hide them.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-7 Components and Layouts

Fig. 3.1.4 Tool window bars


Clicking on a button will display the corresponding tool window while a second click will hide the
window. Buttons prefixed with a number (for example 1: Project) indicate that the tool window may
also be displayed by pressing the Alt key on the together with the corresponding number. The
location of a button in a tool window bar indicates the side of the window against which the window
will appear when displayed. These positions can be changed by clicking and dragging the buttons to
different locations in other window tool bars.Each tool window has its own toolbar along the top edge.
The buttons within these toolbars vary from one tool to the next, though all tool windows contain a
settings option, represented by the cog icon,which allows various aspects of the window to be
changed.

Fig. 3.1.5 Settings menu for the project view tool window
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-8 Components and Layouts

Fig. 3.1.5 shows the settings menu for the project versions of the application, or multiple builds to
view tool window(pointed by arrow). Options are target different device categories).
available, for example, to undock a window and to
TODO - As the name suggests, this tool provides a
allow it to float outside of the boundaries of the
place to review items that have yet to be completed
Android Studio main window and to move and
on the project. Android Studio compiles this list by
resize the tool panel.
scanning the source files that make up the project to
All of the windows also include a far right button look for comments that match specified TODO
on the toolbar providing an additional way to hide patterns. These patterns can be reviewed and
the tool window from view. A search of the items changed by selecting the File -> Settings… menu
within a tool window can be performed simply by option and navigating to the TODO page listed
giving that window focus by clicking in it and then under Editor.
typing the search term (for example the name of a
Messages - The messages tool window records
file in the Project tool window). A search box will
output from the Gradle build system (Gradle is the
appear in the window's tool bar and items matching
underlying system used by Android Studio for
the search highlighted.Android Studio offers a wide
building the various parts of projects into runnable
range of window tool windows, the most commonly
applications) and can be useful for identifying the
used of which are as follows:
causes of build problems when compiling application
Project - The project view provides an overview of projects.
the file structure that makes up the project allowing
Android Monitor - The Android Monitor tool
for quick navigation between files. Generally, double
window provides access to the Android debugging
clicking on a file in the project view will cause that
system. Within this window tasks such as monitoring
file to be loaded into the appropriate editing tool.
log output from a running application, taking
Structure - The structure tool provides a high level screenshots and videos of the application,stopping a
view of the structure of the source file currently process and performing basic debugging tasks can be
displayed in the editor. This information includes a performed. The tool also includes real-time GPU,
list of items such as classes, methods and variables in networking, memory and CPU usage monitors.
the file. Selecting an item from the structure list will
Android Model - The Android Model tool window
take you to that location in the source file in the
provides a single location in which to view an
editor window.
exhaustive list of the different options and settings
Captures - The captures tool window provides access configured within the project. These can range from
to performance data files that have been generated by the more obvious settings such as the target
the monitoring tools contained within the Android Android SDK version to more obscure values such
Monitor tool window. as build configuration rules.

Favorites - A variety of project items can be added to Terminal - Provides access to a terminal window on
the favorites list. Right-clicking on a file in the project the system on which Android Studio is running. On
view, for example, provides access to an Add to Windows systems this is the Command Prompt
Favorites menu option. Similarly, a method in a interface, while on Linux and Mac OS X systems this
source file can be added as a favourite by takes the form of a Terminal prompt.
right-clicking on it in the Structure tool window.
Run - The run tool window becomes available when
Anything added to a Favorites list can be accessed
an application is currently running and provides a
through this Favorites tool window.
view of the results of the run together with options
Build Variants - The build variants tool window to stop or restart a running process.If an application
provides a quick way to configure different build is failing to install and run on a device or emulator,
targets for the current application project (for this window will typically provide diagnostic
example different builds for debugging and release information relating to the problem.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3-9 Components and Layouts

Event Log - The event log window displays messages relating to events and activities performed
within Android Studio. The successful build of a project, for example,or the fact that an application is
now running will be reported within this tool window.

Gradle Console - The Gradle console is used to display all output from the Gradle system as projects
are built from within Android Studio. This will include information about the success or otherwise of
the build process together with details of any errors or warnings.

Gradle - The Gradle tool window provides a view onto the Gradle tasks that make up the project
build configuration. The window lists the tasks that are involved in compiling the various elements of
the project into an executable application. Right-click on a top level Gradle task and select the Open
Gradle Configmenu option to load the Gradle build file for the current project into the editor.

3. Fundamental User Interface Design : Anroid Studio provides an easy way of designing user
interfaces. The file named "activity_main.xml" located under the "res/layout" folder contains all the
layout information of the current activity. If we try to open an .xml file outside of Android Studio,
it is opened by a text editor or a browser. However, when we open an .xml file in Android Studio,
it reads the .xml file and shows the corresponding activity layout with its components. In order to
open the activity_main.xml in Android Studio, double-click on it in the project explorer and the
activity layout will be displayed in the middle pane as shown below :

Fig. 3.1.6 Layout of the activity

As you can see, the layout of the activity is shown in the middle pane. The name of the app appears at
the top of the activity. The default empty activity contains a default text which is shown inside the
circle in the above figure. At the left top of the middle pane, there exists a tab called "Palette" indicated
inside the rectangle in the figure. When we click on this tab, the palette shown in Figure Fig. 3.1.7
appears from which we can add all possible user interface objects and layout templates to the activity.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 10 Components and Layouts

Fig. 3.1.7 The component palette


When the palette tab is clicked, two panes are opened: the Palette shown by the upper rectangle and
the Component Tree pane inside the lower rectangle in Figure Fig. 3.1.7. The Palette contains several
groups like Widgets, Text Fields and Layouts. We can easily drag and drop these components to the
user interface. On the other hand, the Component Tree lists the activity's components in a hierarchical
manner. As you can see from Fig. 3.1.7, Android Studio already placed a "Hello World" text at the top
left of the view.

Let's position this text, comprised of a TextView widget, to the middle of the view. For this, select this
TextView and then drag and drop to the middle by the help of the guiding lines as shown below :

Fig. 3.1.8 Drag and drop operation on the TextView


®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 11 Components and Layouts

After the drag and drop operation, the TextView will be kept selected. We can now change the
properties of the TextView using the Properties pane which is at the right of the Layout view as shown
inside the rectangle in Fig. 3.1.9. Click the arrow shown inside the circle in this figure to open the basic
editable properties of the TextView.

Fig. 3.1.9 The Properties pane


The editable properties of the TextView component are shown inside the rectangle in Figure.
4. Building the Project and Running on an Emulator : To run our first Android app on an emulator
follow the steps given below :
i) Building the project, ii) Selecting the emulator
iii) Run our app on the emulator.

Fig. 3.1.10 The editable properties of the TextView


®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 12 Components and Layouts

In order to build and run the project, please click the "Run" button as indicated by the arrow in
Fig. 3.1.10 The emulator and device selection dialog shown in Fig. 3.1.11 will appear. When the
emulator starts running, you will see a Nexus 5 screen as shown in Fig. 3.1.12.

Fig. 3.1.11 Selecting the target for running our first app

Fig. 3.1.12 The Nexus 5 emulator

3.1.2 Directory and File Structure of an Android Studio Project


The file structure of an Android project can be viewed in various forms in Android Studio. The button
just at above the left pane (shown by the arrow) is used to open the selection box for choosing the
preferred method of viewing the file hierarchy as shown in Fig. 3.1.13. The default file viewer is the
"Android" mode.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 13 Components and Layouts

Fig. 3.1.13 Switching among different ways of viewing files and folders

When the selection is the "Android" mode, the default files and folders shown in Fig. 3.1.14

Fig. 3.1.14 Default folder and file structure of an Android project

You can use the arrows (shown inside the circle in the figure)for viewing the contents of folders. The
default folders (shown inside the rectangles in Fig. 3.1.14) and their contents are explained as follows :

1. manifests folder : This folder has the AndroidManifest.xml file inside. This file contains the
configuration parameters of the project such as permissions, services and additional libraries.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 14 Components and Layouts

2. java folder : The source code files written in Java programming language reside in this folder. You
can see that the java file of the activity named "MainActivity.java" is automatically created in this
folder.
3. res folder : The resource files are contained in this folder. Resources basically mean all the needed
files except the source code. The media, image and layout files residing in the resources folder are
accessed via Java code written in MainActivity.java.
The floder structure includes different types Clik on the arrow
of files here and choose
the project option
If you browse through the folder structure, to see the files and
you'll see that the wizard has created various folders that make
up your project
types of files and floders for you :
This is the
· Java and XML soure files : These are the name of
activity and layout files for your app. the project

· Android-generated Java files : There are some


extra Jave files you don't need to touch that
Android STudio generates for you
automatically.
· Resource files : These include default image
files for icons, styles your app might use and
These files and
any common String values your app might folders are all
want to look up. included in your
project
· Android libraries : In the wizard, ou specified
the minimum SDK version you want your app
to be compatible with. Android Studio makes
sure your app includes the relevant Android
libraries for that version.
· Configuration files : The configuration files
tell Android what's actually in the app and
how it should run.
Fig. 3.1.15 File structure of an Android project

Some of the key files and directory(folders) are as shown in Fig. 3.1.16 : (See Fig. on next page)

Let's see each folder in detail :


· src - Java source files associated with your project. This includes the Activity "controller" files as well
as your models and helpers.
· res - Resource files associated with your project. All graphics, strings, layouts, and other resource files
are stored in the resource file hierarchy under the res directory.
· res/layout - XML layout files that describe the views and layouts for each activity and for partial
views such as list items.
· res/values - XML files which store various attribute values. These include strings.xml, dimens.xml,
styles.xml, colors.xml, themes.xml, and so on.
· res/drawable - Here we store the various density-independent graphic assets used in our application.
· res/drawable-hdpi - Series of folders for density specific images to use for various resolutions.
· res/mipmap - most commonly used for application icons.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 15 Components and Layouts

The app folder is a


module in your project.
MyFirstApp

The build folder contains files that


The root folder is the Android studio creates for you. You
name of your project. app don't usually edit anything in this folder.
All the files for your
project go in here.
build

Every Android project needs a file


generated/source called R. java, which is created for
you and which lives in the generated/
source folder. Android uses this file
to keep track of resources in the app.
ridebug

com/hfad/myfirstapp
arc
The src folder contains
source code you write
and edit. R.java
main

The java folder contains any java


Java code you write. Any
activities you create live here.
com/hfad/myfirstapp
MainActivity. java defines
You can find app resources in the an activity. An activity tells
res folder. For example, the layout Android how the app should
subfolder contains layouts, and the interact with the user.
values subfolder contains resource MainActivity.java
files for values such as Strings. You
can get other types of resources too.
res

layout activity_main.xml defines a


layout. A layout tells Android
how your app should look.
activity_main.xml

Every Android app must


include a file called strings.xml is a String resource
values
AdroidManifest.xml at its file. It includes Strings such as the
root. The manifest file app's name and any default text
contains essential information values. Other files such as layouts
about the app. such as what strings.xml and activities can look up text
components it contains, required values from here.
libraries, and other declarations.
AndroidManifest.xml
Fig. 3.1.16 Directory structure of an Android project
The most frequently edited files are :
· res/layout/activity_foo.xml - This file describes the layout of the activity's UI. This means the
placement of every view object on one app screen.
· src/.../FooActivity.java - The Activity "controller" that constructs the activity using the view, and
handles all event handling and view logic for one app screen.
· AndroidManifest.xml - This is the Android application definition file. It contains information about
the Android application such as minimum Android version, permission to access Android device
capabilities such as internet access permission, ability to use phone permission, etc.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 16 Components and Layouts

Other less edited folders include : 1. Activities : Activities are said to be the
· gen - Generated Java code files, this library is for presentation layer of our applications. An activity
Android internal use only. is the first stepping stone is building an Android
· assets - Uncompiled source files associated with
user application. The UI of our application is
your project; Rarely used. build around one or more extensions of the
Activity class.
· bin - Resulting application package files associated
An activity in android is like your computer
with your project once it's been built.
welcome screen which presents single user
· libs - Before the introduction of Gradle build display. In other words, Activity in android
system, this directory was used for any secondary represents single screen with a user interface. We
libraries (jars) you might want to link to your app. can understand Activity in terms of web
applications For example: We creates numbers of
3.2 Components of Android Application
web pages to build complete web application,
Almost all popular applications are interactive. These similarly on the other hand android application
applications interact with the user, and, depending on consist of several Activities to run as a complete
the data supplied by the user, desired actions and/or application. There is one "main" activity. All
processing are performed. The user interface controls other activities are child activities. There is a
thus play a major role in getting feedback from the stack called back stack. Whenever, there is a new
user. Application components are the ones which window is started, previous activity is pushed to
when combined together, offers you a brilliant the back stack and it is stopped until the new
Android application. So, these components exactly act activity is done. As soon as the back key of your
as the building blocks of an Android application. The device is pressed, new activity is popped out of
information regarding all the application components stack and destroyed. Now previous activity
is provided in the manifest file, which is resumes.
AndroidManifest.xml. This file will help you in 2. Services : These are like invisible workers of our
understanding the use of each and every application app. These components run at backend, updating
component and how do they interact with each other. your data sources and Activities, triggering
Notification and also broadcast Intents. They also
Android provides four important components to
perform some tasks when applications are not
build any android application.
active. This component is responsible for
· Activities
handling the time taking operations which
· Services
generally runs in the background of the
· Intent and broadcast receivers operating system (in this case, Android). The
· Content Providers simple example of the service component is that
Activities when you play music on your mobile phone, you
Views / User interface Must have in any app will be able to use other applications too. A
Intents service can take two forms:
a. Started : After a service starts, it can run
indefinitely and usually performs single
Services
operation. No result is returned to user. For
Content provider Can have in any app
example, uploading a file. After the task is
Broadcast receiver
completed, it should terminate itself.
Activities Intents and broadcast b. Bound : In this case, a component is bound
receivers
to a service so that a particular task can be
Widgets and notifications completed. This type of service provides a
client-server like interface. Requests can be
send, receive requests, and return result to
Services Content providers
the user. Inter process communication is
Fig. 3.2.1 Components of android application achieved through this service.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 17 Components and Layouts

3. Intents and Broadcast Receivers - Android Intent is the message that is passed between
components such as activities, content providers, broadcast receivers, services etc. It is generally
used with startActivity( ) method to invoke activity, broadcast receivers etc. It binds individual
components to each other. Broadcast Receivers simply respond to broadcast messages from other
applications or from the system itself. These messages are sometime called events or intents. For
example, applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver who
will intercept this communication and will initiate appropriate action. another example is, when
your device boots up or switched on, the system generates a broadcast to all apps. There should be
a procedure or should be something which can receive these broadcasts. These receptors are called
broadcast receivers. There are two types of broadcasts:
a. Normal Broadcasts : These are asynchronous in nature. Many receivers can be activated at the
same time which doesn't have any defined order. But they are very efficient.
b. Ordered Broadcasts : They are synchronous in nature. Broadcast received by one receiver passes
it to other receivers. Broadcasts are delivered to receiver on one-to-one and sequential basis. Either
receiver will pass result to another receiver or it may completely destroy the broadcast.
4. Content Providers - It is used to manage and persist the application data also typically interact
with SQL database. They are also responsible for sharing the data beyond the application
boundaries. The Content Providers of a particular application can be configured to allow access
from other applications, and the Content Providers exposed by other applications can also be
configured. With content providers we can save data in SQLite database, on the web or any other
persistent storage location, where application can easily access the data. This component is useful in
reading and writing private data. For example: we can read and write important reminders or
notes in database(within an application).
5. Android Widgets and Notifications : Android App widgets are the small application views. These
views can be embedded into other applications. They can receive updates on periodic basis. A
widget is a quick view of your app's functionality and data. This view is accessible from home
screen of your device. Now widgets are of following types :

Widgets

Informational widgets Collection widgets Control widgets Hybrid widgets

Fig. 3.2.2 Types of widgets


a. Informational Widget : These Android widgets are going to display only that information to
user which is important and dynamic in nature. Example the information displayed on your
home screen saying time and weather condition is a widget of this type.
b. Collection Widgets : These Android widgets scroll in top-to-down direction. Collection of
information of same type and then enabling user to open any one of them to full detail.
Example is your e-mail app which will display all the mails in your inbox and then allow you
to open any one o them.
c. Control Widgets : Displays the most frequently used functionalities which user might want to
control from home screen. For example in a video app, you can pause, play, stop, go to
previous track, move to next track is an example of control widget.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 18 Components and Layouts

d. Hybrid Widgets : These Android widgets The third approach, the combined approach, is highly
combine features of all of the above three. preferred.
· Notification, as the name says keeps the user aware
The graphical user interface for an Android app is
of events going on. User is kept informed like any
built using a hierarchy of View and ViewGroup
news channel. For e.g, everyone of us know about
objects.
facebook or whatsapp, now notification system of
· A View is an interactive UI component (or widget
app is responsible for informing you about any new
or control), such as button and text field. It controls
friend request, chat request, or a new message from
a rectangular area on the screen. It is responsible for
say, dvs or xyz, etc.
drawing itself and handling events (such as clicking,
There are a few other application components that
entering texts). Android provides many ready-to-use
you should be aware of. These application
Views such as TextView, EditText, Button,
components include fragments, views, layouts,
RadioButton, etc, in package android.widget. You
intents, resources, and manifest. All of these
can also create your custom View by extending
components are used for the creation of above
android.view.View.
components.
· A ViewGroup is an invisible container used to layout
Application the View components. Android provides many
S.No. Description
Components ready-to-use ViewGroups such as LinearLayout,
1 Fragments Represents the fragments of
RelativeLayout, TableLayout and GridLayout in
a user interface in the package android.widget. You can also create your
Activity component custom ViewGroup by extending from
2 Views Includes the user interface android.view.ViewGroup.
elements like buttons, Views and ViewGroups are organized in a single tree
drop-down lists, etc. structure called view-tree. You can create a view-tree
3 Layouts Controls the screen format either using programming codes or describing it in a
based on different XML layout file.
hierarchies of the views
Takes care of the
appearance of the views on Layout view groups
the screen
android.view.View
4 Intents Wires the messages of
different components Layouts are a type of
together ViewGroup. ViewGroup
is a subclass of View.
android.view.ViewGroup
5 Resources Includes external elements
like drawable or editable
pictures, strings, and
constants
android.widget. android.widget.
LinearLayout FrameLayout
3.2.1 Creating the user Interface
There are three approaches to creating user interfaces The views for a screen are organized in a hierarchy.
in Android. At the root of this hierarchy is a ViewGroup that
1. You can create user interfaces entirely in Java contains the layout of the entire screen. The view
code group's child screens can be other views or other
view groups as shown in the following figure.
2. Entirely in XML
3. Combining both methods (defining the user 1. The root view group.
interface in XML and then referring and 2. The first set of child views and view groups
modifying it through Java code). whose parent is the root.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 19 Components and Layouts

ViewGroup 1 The following is list of some commonly used controls


in Android applications :
· TextView : A read-only text label. It supports
ViewGroup View View 2 multiline display, string formatting, and automatic
word wrapping.
· EditText : An editable text box that also accepts
View View View multiline entry and word-wrapping.
Fig. 3.2.3 ViewGroup objects form branches in the · ListView : A ViewGroup that creates and manages
layout and contain other View objects. a vertical list of views, displaying them as rows
Commonly Used Layouts And Controls : within the list.
The views or the controls that we want to display in · Spinner : A TextView and an associated list of
an application are arranged in an order or sequence items that allows us to select an item from the list
by placing them in the desired layout. The layouts to display in the text box.
also known as Containers or ViewGroups. These are · Button : A standard command button.
used for organizing the views or controls in the · CheckBox : A button allowing a user to select
required format. Android provides the following (check) or unselect (uncheck).
layouts · RadioButton : A mutually exclusive button, which,
· LinearLayout : In this layout, all elements are when selected, unselects all other buttons in the
arranged in a descending column from top to group.
bottom or left to right. Each element contains
properties to specify how much of the screen space
3.3 Layouts
it will consume. Depending on the orientation
parameter, elements are either arranged in row or Layouts are basically containers for other items
column format. known as Views , which are displayed on the screen.
· RelativeLayout : In this layout, each child element Layouts help manage and arrange views as well.
is laid out in relation to other child elements. That Layouts are defined in the form of XML files that
is, a child element appears in relation to the cannot be changed by our code during runtime.
previous child. Also, the elements are laid out in
Following table shows the layout managers provided
relation to the parent.
by the Android SDK.
· AbsoluteLayout : In this layout, each child is given
a specific location within the bounds of the parent Layout Manager Description
layout object. This layout is not suitable for devices
with different screen sizes and hence is deprecated. LinearLayout Organizes its children either
horizontally or vertically
· FrameLayout : This is a layout used to display a
single view. Views added to this are always placed RelativeLayout Organizes its children relative to
one another or to the parent
at the top left of the layout. Any other view that is
added to the FrameLayout overlaps the previous AbsoluteLayout Each child control is given a
view; that is, each view stacks on top of the specific location within the bounds
previous one. of the container

· TableLayout : In this layout, the screen is assumed FrameLayout Displays a single view; that is, the
to be divided in table rows, and each of the child next view replaces the previous
view and hence is used to
elements is arranged in a specific row and column.
dynamically change the children in
· GridLayout : In this layout, child views are the layout
arranged in a grid format, that is, in the rows and
TableLayout Organizes its children in tabular
columns pattern. The views can be placed at the form
specified row and column location. Also, more than
one view can be placed at the given row and GridLayout Organizes its children in grid
format
column position.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 20 Components and Layouts

Layouts

Linear layout Relative layout Table layout Frame layout Grid layout Absolute layout

Fig. 3.3.1 Layouts supported by android system

Let's get familiar with the layout editor :

The layout editoris used to edit the layout file. You can drag and drop view objects into a graphical
pane, and arrange, resize, and specify properties for them. You immediately see the effect of changes
you make.

To use the layout editor, open the XML layout file. The layout editor appears with the Design tab at
the bottom highlighted.

(If the Text tab is highlighted and you see XML code, click the Design tab.) For the Empty Activity
template, the layout is as shown in the figure below.

Fig. 3.3.2 The layout editor window

In the Fig. above :

1. XML layout file : The XML layout file, typically named activiy_main.xml file.Double-click it to
open the layout editor.
2. Palette of UI elements (views) : The Palette pane provides a list of UI elements and layouts.Add
an element or layout to the UI by dragging it into the design pane.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 21 Components and Layouts

3. Design toolbar : The design pane tool bar provides buttons to configure your layout appearance in
the design pane and to edit the layout properties.See the figure 3.3.6 for details.
4. Properties pane : The Properties pane provides property controls for the selected view.
5. Property control : Property controls correspond to XML attributes. Shown in the figure is the Text
property of the selected TextView, set to Hello World!.
6. Design pane : Drag views from the Palette pane to the design pane to position them in the layout.
7. Component Tree : The Component Tree pane shows the view hierarchy. Click a view or view
Group in this pane to select it.The figure shows the TextView selected.
8. Design and Text tabs Click Design to see the layout editor, or Text to see XML code.The layout
editor's design toolbar offers a row of buttons that let you configure the appearance of the layout :

Fig. 3.3.3 Design toolbar

In the figure above :

1. Design, Blueprint and Both : Click the Design icon (first icon) to display a color preview of your
layout. Click the Blueprint icon (middle icon) to show only outlines for each view. You can see
both views side by side by clicking the third icon.
2. Screen orientation : Click to rotate the device between landscape and portrait.
3. Device type and size : Select the device type (phone/tablet, Android TV, or Android Wear) and
Screen configuration (size and density).
4. API version : Select the version of Android on which to preview the layout.
5. App theme : Select which UI theme to apply to the preview.
6. Language : Select the language to show for your UI strings. This list displays only th languages
available in the string resources.
7. Layout Variants : Switch to one of the alternative layouts for this file, or create a new one.

3.3.1 Android Linear Layout


· In android, LinearLayout is a ViewGroup subclass which is used to render all child View instances
one by one either in Horizontal direction or Vertical direction based on the orientation property.
· Linear layout in Android allow us to arrange components horizontally in a single column or vertically
in a single row. Vertically or horizontally direction depends on attribute android : orientation.
· Linear layout is simple and easy to use, it creates a scroll bar if the length of the window exceeds the
length of the screen. Vertically linear layout has only one item per row.
· Linear layout has many different attributes which can be used to customize linear layout according to
needs.
· There are two types of linear layout orientation :
1. Vertical 2. Horizontal

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 22 Components and Layouts

Fig. 3.3.4 Types of layouts


1. Vertical : In this all the child are arranged vertically in a line one after the other.
2. Horizontal : In this all the child are arranged horizontally in a line one after the other.

Android LinearLayout Declaration :

LinearLayout xmlns : android=”http://schemas.android.com/apk/res/android”


android : layout_width=”match_parent” The layout_width and layout_height specify
android : layout_height=”match_parent” what size you want the layout to be
You use
<LinearLayout> android : orientation=”vertical”
to define a linear The orientation specifies
layout ...> whether you want to display
... There may be views vertically or horizontally
other attributes too
</LinearLayout>

In above code snippet, the orientation is defined as vertical, so this aligns all its child layout / views
vertically.

Android LinearLayout Example


Following is the example of creating a LinearLayout with different controls in android application.

Steps :

1. Create a new android application using android studio and give names as LinearLayout.
2. Now open an activity_main.xml file from \res\layout path and write the code like as shown below:

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:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 23 Components and Layouts

android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send"/>
</LinearLayout>
3. After creation of layout, load the XML layout resource from activity onCreate() callback
method,for that open main activity file Output :

MainActivity.java from \java\com.vrs.linearlayout path and


write the code like as shown below.
MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Attributes of linear layout
Following are some attributes of linear layout of Android.

Attribute Description

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

android:layout_width This is the width of the layout.

android:layout_height This is the height of the layout

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 24 Components and Layouts

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

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

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

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

android:layout_gravity This specifies how child Views are positioned.

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

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

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

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

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

oandroid:paddingTop This is the top padding filled for the layout.

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

1. Orientation :
· The orientation attribute used to set the childs/views horizontally or vertically.
· In Linear layout default orientation is vertical.
· The valid values for this attribute are horizontal and vertical.
· If the value of the android:orientation attribute is set to vertical , the children in the linear layout are
arranged in a column layout, one below the other.
· If the value of the android:orientation attribute is set to horizontal, the controls in the linear layout
are arranged in a row format, side by side.
· The orientation can be modified at runtime through the setOrientation() method. That is, by supplying
the values HORIZONTAL or VERTICAL to the setOrientation() method, we can arrange the children
of the LinearLayout in row or column format, respectively as shown below :
For vertical -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"> <!-- Vertical Orientation set -->
<!-- Put Child Views like Button here -->
</LinearLayout>
For horizontal -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <!-- Horizontal Orientation set -->
<!-- Child Views are here -->
</LinearLayout>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 25 Components and Layouts

Example 1 : Orientation vertical :


<LinearLayout 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:orientation="vertical"
tools:context=".LinearLayout" >

<Button
android:text="BUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content" Output

/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 1"
android:paddingTop="10px"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 2"
android:paddingTop="10px"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 3"
android:paddingTop="10px"/>

</LinearLayout>

Example 2 : Orientation Horizontal :


<LinearLayout 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:orientation="horizontal"
tools:context=".LinearLayout" >

<Button
android:text="BUTTON"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 26 Components and Layouts

Output

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 1"
android:paddingTop="10px"
android:paddingLeft="10px"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 2"
android:paddingTop="10px"
android:paddingLeft="10px"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text 3"
android:paddingTop="10px"
android:paddingLeft="10px"/>
</LinearLayout>

2. gravity :
· The gravity attribute is an optional attribute for aligning the content within a control. For example, to
align the text of a control to the right, we set the value of its android:gravity attribute to right .
· The valid options for android:gravity include left, center, right, top, bottom,
center_horizontal , center_vertical , fill_horizontal , and fill_vertical.
· The task performed by few of the above options is as follows :
¡ center_vertical : Places the object in the vertical center of its container, without
changing its size
¡ fill_vertical : Grows the vertical size of the object, if needed, so it completely fills its container
¡ center_horizontal : Places the object in the horizontal center of its container,without changing its size
¡ fill_horizontal : Grows the horizontal size of the object, if needed, so it completely fills its container
¡ center : Places the object in the center of its container in both the vertical and horizontal axis,
without changing its size

Example :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal">
<!--Button Child View Here--->

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 27 Components and Layouts

Output

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click2"
android:id="@+id/click2"
android:background="#0e7d0d" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click1"
android:id="@+id/click"
android:background="#761212" />
</LinearLayout>

3. layout_weight :
· The layout weight attribute specify each child control's relative importance within the parent linear
layout.
· The weight attribute affects the size of the control. That is, we use weight to assign the capability to
expand or shrink and consume extra space relative to the other controls in the container.
· The values of the weight attribute range from 0.0 to 1.0 , where 1.0 is the highest value. Let's suppose
a container has two controls and one of them is assigned the weight of 1. In that case, the control
assigned the weight of 1 consumes all the empty space in the container, whereas the other control
remains at its current size. If we assign a weight of 0.0 to both the controls, nothing happens and the
controls maintain their original size.
· If both the attributes are assigned the same value above 0.0, both the controls consume the extra space
equally. Hence, weight lets us apply a size expansion ratio to the controls.
Example :
<?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="horizontal">
<!--Add Child View Here--->
<Button Output
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Weight 2"
android:background="#5b39c6"
android:layout_margin="5dp"
android:id="@+id/button"
android:layout_weight="2" />
<Button
android:layout_width="wrap_content"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 28 Components and Layouts

android:layout_height="wrap_content"
android:background="#00ff00"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Weight 1" />
</LinearLayout>

4. WeightSum :
· weightSum is the sum up of all the child attributes weight.
· This attribute is required if we define weight property of the childs.
Example :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="3"
android:orientation="horizontal">
<!--Add Child View Here--->
</LinearLayout>

5. layout_width and layout_height :


· The default height and width of a control are decided on the basis of the text or content that is
displayed through it.
· To specify a certain height and width to the control, the android:layout_width and
android:layout_height attributes is used.
· The values for the height and width attributes can be specified in the following three ways :
¡ By supplying specific dimension values for the control in terms of px (pixels), dip/dp (device
independent pixels), sp (scaled pixels), pts (points), in (inches), and mm (millimeters). For example,
the android:layout_width="20px" attribute sets the width of the control to 20 pixels.
¡ By providing the value as wrap_content. When assigned to the control's height or width, this
attribute resizes the control to expand to fit its contents. For example, when this value is applied to
the width of the TextView , it expands so that its complete text is visible.
¡ By providing the value as match_parent. When assigned to the control's height or width, this
attribute forces the size of the control to expand to fill up all the available space of the enclosing
container.
· For layout elements, the value wrap_content resizes the layout to fit the controls added as its children.
The value match_parent makes the layout expand to take up all the space in the parent layout.
· It will control the width and height of the linear layout.
¡ If you want to give full width and height then set layout_width and layout_height as match_parent.
¡ Set layout_width and layout_height as wrap_content if you want to have width of linearlayout as
per requirements of children widgets.
¡ You can set layout_width in units also. For example 10dp,20dp etc.
¡ The higher the dp number the more width is there.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 29 Components and Layouts

6. Applying the padding Attribute :


· The padding attribute is used to increase the whitespace between the boundaries of the control and its
actual content.
· Through the android:padding attribute, we can set the same amount of padding or spacing on all four
sides of the control.
· Similarly, by using the android:paddingLeft , android:paddingRight , android:paddingTop , and
android:paddingBottom attributes, we can specify the individual spacing on the left, right, top, and
bottom of the control, respectively.
· For example-1) To add padding of 16dp to all edges of the layout :
< LinearLayout …
android:padding="16dp:> ¬ This ads the same padding to all edges of the layout
< LinearLayout>
padding

padding

Layout

padding

padding

2) Different amounts of padding to different edges


< LinearLayout> … ü
ï
androdi : paddingBottom="16dp" ï
androdi : paddingLeft="16dp" ý Add padding to the individual edges
ï
androdi : paddingRight="16dp" ïþ
androdi : paddingTop="16dp"
< LinearLayout>
paddingTop

paddingLeft

Layout

paddingRight

paddingBottom

· To set the padding at runtime, we can call the setPadding() method.


Example 1 : First we will design Android Linear Layout without using weight property

In this example we have used one TextView and 4 Button. The orientation is set to vertical.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 30 Components and Layouts

Below is the code of activity_main.xml


<!-- Vertical Orientation is set -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Text Displayed At Top -->

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Linear Layout (Without Weight)"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />

<!-- Button Used -->

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300" />

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
Output
android:background="#e6cf00" />

<Button Linear Layout (Without Weight)


android:layout_width="fill_parent" BUTTON 1
android:layout_height="wrap_content"
BUTTON 2
android:text="Button 3"
android:background="#0472f9" /> BUTTON 3

BUTTON 4
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5" />
</LinearLayout>
Example 2 : In this example of linear layout we have used weight property.

Below is the code of activity_main.xml with explanation included


<!-- Vertical Orientation is set with weightSum-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 31 Components and Layouts

android:weightSum="5"
android:orientation="vertical">

<!-- Text Displayed At Top -->

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Linear Layout (With Weight)"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="0"/>

<!-- Button Used -->

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300"
android:layout_weight="1"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00"
Output
android:layout_weight="1"/>
Linear Layout (With Weight)
<Button
BUTTON 1
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
BUTTON 2
android:background="#0472f9"
android:layout_weight="1"/>
BUTTON 3
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content" BUTTON 4
android:text="Button 4"
android:background="#e100d5"
android:layout_weight="1"/>
</LinearLayout>
Example 3 : Mixed Example With Horizontal And Vertical Orientation Properties :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 32 Components and Layouts

android:layout_gravity="center"
android:orientation="vertical"
tools:context=".LinearLayout" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10px"
android:paddingTop="20px"
android:text="LOGIN" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20px">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10px"
android:paddingTop="20px"
android:text="Username" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:layout_marginLeft="40px"
android:paddingTop="20px" />

</LinearLayout>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20px"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:paddingTop="20px"
android:paddingLeft="10px"/>

<EditText

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 33 Components and Layouts

android:layout_width="wrap_content" Output
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="40px"
android:layout_weight="0.50"
android:paddingTop="20px" />

</LinearLayout>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="20px"
android:paddingTop="10px"
android:text="BUTTON" />
</LinearLayout>

3.3.2 Android Absolute Layout


Android Absolute Layout is a layout type that allows to position the views in the screen using the X,
Y coordinates.
· Absolute Layout enables you to specify the exact location of its children.
· In order to align the views in the screen using absolute layout is very difficult because we have to
manually specify the locations of the screen accurately. That is why Absolute layouts are less flexible
and harder to maintain than other types of layouts in
Absolute layout
android.
(20, 35)
· Each child in an AbsoluteLayout is given a specific location
within the bounds of the container.
(100, 85)
· Such fixed locations make AbsoluteLayout incompatible with
devices of different screen size and resolution.
(15, 185)
· The controls in AbsoluteLayout are laid out by specifying
their exact X and Y positions. The coordinate 0,0 is the origin
and is located at the top-left corner of the screen. Fig. 3.3.5

Android AbsoluteLayout Attributes :


Following are the important attributes of android AbsoluteLayout.
android:id : This is the ID which uniquely identifies the layout.
android:layout_x : This specifies the x-coordinate of the view.
android:layout_y : This specifies the y-coordinate of the view.

Absolute Layout xml snippet


<AbsoluteLayout
android:layout_width="50dp"
android:layout_height="wrap_content
android:layout_x="25px"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 34 Components and Layouts

android:layout_y="29px">
</AbsoluteLayout>

Android AbsoluteLayout Syntax Code :


<AbsoluteLayout android:id="@+id/absoluteLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</AbsoluteLayout>
Example1 :
activity_main.xml
<AbsoluteLayout android:id="@+id/absoluteLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/btn1"
android:text="Login"
android:textColor="@color/colorPrimary"
android:layout_x="50px"
android:layout_y="361px" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/btn2"
android:textColor="@color/colorPrimary"
android:text="Register"
android:layout_x="350px"
android:layout_y="361px" />

</AbsoluteLayout>
The graphical representation of the above code is as follows.

Example 2 : Layout File activity_absolute_layout_app.xml on Arranging Controls in the AbsoluteLayout


Container
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Student Registration Form"
android:textSize="20sp"
android.textStyle="bold"
android:layout_x="90dip"

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 35 Components and Layouts

android:layout_y="2dip"/> The controls in activity_absolute_layout_app.xml are


<TextView as follows :
android:layout_width="wrap_content"
· The Student Registration Form TextView is set to
android:layout_height="wrap_content"
appear 90dip from the left and 2dip from the top
android:text="Student ID:"
android:layout_x="5dip" side of the container. The size of the text is set to
android:layout_y="40dip" /> 20sp, and its style is set to bold .
<EditText · The Student ID TextView is set to appear 5dip from
android:id="@+id/student_is" the left and 40dip from the top side of the
android:layout_width="wrap_content"
container.
android:layout_height="wrap_content"
android:minWidth="100dip" · The student_id EditText control is set to appear
android:layout_x="110dip" 110dip from the left and 30dip from the top side of
android:layout_y="30dip" /> the container. The minimum width of the control is
<TextView set to 100dp.
android:layout_width="wrap_content"
· The Student Name TextView control is set to appear
android:layout_height="wrap_content"
5dip from the left and 90dip from the top side of
android:text="Student Name:"
the container.
android:layout_x="5dip"
android:layout_y="90dip"/> · The student_name EditText control is set to appear
<EditText 110dip from the left and 80dip from the top side of
android:id="@+id/student_name" the container. The minimum width of the control is
android:layout_width="200dip" set to 200dip, and its text is set to scroll horizontally
android:layout_height="wrap_content"
when the user types beyond its width.
android:minWidth="200dip"
android:layout_x="110dip" · The Marks TextView is set to appear 5dip from the
android:layout_y="80dip" left and 140dip from the top side of the container.
android:scrollHorizontally="true" /> · The marks EditText control is set to appear 110dip
<TextView from the left and 130dip from the top side of the
android:layout_width="wrap_content"
container. The minimum width of the control is set
android:layout_height="wrap_content"
to 100dip .
android:text="Marks:"
android:layout_x="5dip" · The click_btn Button, Add New Student, is set to
android:layout_y="140dip" /> appear 80dip from the left and 190dip from the top
<EditText side of the container.
android:id="@+id/marks" If we don't specify the x, y coordinates of a control in
android:layout_width="wrap_content"
AbsoluteLayout, it is placed in the origin point, that
android:layout_height="wrap_content"
is, at location 0,0. If the value of the x and y
android:minWidth="100dip"
android:layout_x="110dip"
coordinates is too large, the control does not appear
android:layout_y="130dip" /> on the screen. The values of the x and y coordinates
<Button are specified in any units, such as sp, in, mm, and pt.
android:layout_width="wrap_content" After specifying the locations of controls in the layout
android:layout_height="wrap_content" file activity_absolute_layout_app.xml, we can run the
android:id="@+id/click_btn" application. There is no need to make any changes in
android:text="Add New Student" the file AbsoluteLayoutAppActivity.java.
android:layout_x="80dip"
android:layout_y="190dip" />
</AbsoluteLayout>

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 36 Components and Layouts

Output
· Using different tags in frame layout you can also
determine whether to measure all the children or
just those that are in the visible or in the invisible
state when measuring. These can be simply defined
within the XML layout resources and in Java' s for
programmatically application. Understanding layout
and when to use these layouts is important for
good android application design. When this layout
is used correctly, it becomes the fundamental layout
in which many interesting android application user
interfaces can be designed.
¡ When the child content is too large to draw
within the bounds of the layout, it uses the
view scroll view to organise the control within
the interface.
¡ When we need a frame around underlying
views for our interface, then frame layout
provides the foreground draw able facility in
3.3.3 Android Frame Layout
addition to the normal ackground,this task is
done with the help od XML' s attributes.
Frame layout
¡ If multiple child view occurs within the frame
layout then they are drawn in such a order
View such that the last one child view on the top,
which is done using the frame layout.
¡
Frame layout are the normal layout of choice
especially when you want to use the overlapped
view of the design.
Fig. 3.3.6 Frame layout supports one view inside it
· Frame Layout is one of the simplest layout to
· Frame layout is the simple layout representation organize view controls. They are designed to block
used to organise the control within the user an area on the screen.
interface of android application. When we want to
· Frame Layout should be used to hold child view,
display a single item on the display and block out
because it can be difficult to display single views at
the other items then frame layout tool is used.
a specific area on the screen without overlapping
Sometimes it is difficult to organize child views in a
each other.
way that is scalable to different screen sizes without
the children over lapping each other, in that case · Multiple children can be addes to a FrameLayout
the frame layout is used a it can hold a single child and control their position by assigning gravity to
view and can block the other view. each child, using the android:layout_gravity
· We can also add multiple children using frame attribute.
layout and also control their position within this by · FrameLayout is used to display a single View.
simply assigning the gravity tags to each child. In · The View added to a FrameLayout is placed at the
this child view are drawn in the stack with the top-left edge of the layout. Any other View added
feature of stack the recently added is on the top to the FrameLayout overlaps the previous View ;
and also last one added is removed from the top. that is, each View stacks on top of the previous one.
The size of the frame layout depends on the size of
its largest child whether it is visible or not.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 37 Components and Layouts

FrameLayout

Component 1

Component 2

Component 3 Component 4

· Define frame layout using the <FrameLayout> element like this :

FrameLayout xmlns : android=”http://schemas.android.com/apk/res/android”


android : layout_width=”match_parent” These are the same attributes we
android : layout_height=”match_parent” used for our linear layout
You use
<FrameLayout> ...>
to define a frame
layout

This is where you add any views you
wish to stack in the frame layout

</FrameLayout>

Attributes of frame layout :

Lets see different properties of Frame Layout which will be used while designing Android App UI :

1. android:id
· This attribute will give the unique identity to the frame layout.
· When you want to access the frame layout from the JAVA class, this id will give you the reference
via findViewById() method.
· Value of this attribute should be unique across the whole android app to reduce the complexity.
Example to use id:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame"
android:layout_width="200dp"
android:layout_height="300dp"
android:foreground="@color/colorAccent"
tools:context=".MainActivity">

2. android:foreground
· Foreground defines the drawable to draw over the content and this may be a color value.
· Possible color values can be in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb". This all are
different color code model used.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 38 Components and Layouts

Example: To set the blue color for foreground of frameLayout so the ImageView and other child views
of this layout will not be shown.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="fill"
android:foreground="#4363d8"><!--foreground color for a FrameLayout-->

<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>

<!-- Imageview will not be shown because of foreground color which is drawn over it-->

<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>
Output
<!--Textview will not be shown because of foreground color is drawn over it-->

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="vrs"/>

</LinearLayout>
</FrameLayout>

3. android:foregroundGravity
· This defines the gravity to apply to the foreground drawable.
· Default value of gravity is fill.
· We can set values in the form of "top", "center_vertical" , "fill_vertical", "center_horizontal",
"fill_horizontal", "center", "fill", "clip_vertical", "clip_horizontal", "bottom", "left" or "right" .
· It is used to set the gravity of foreground. We can also set multiple values by using "|". Ex:
fill_horizontal|top .Both the fill_horizontal and top gravity are set to framelayout.

4. android:visibility
· We can apply this attribute to any child of the framelayout.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 39 Components and Layouts

· Possible values for visibility are visible, invisible and gone.


¡ Visible means that the view is present and we can also see it.
¡ Invisible means that the view is present and we can not see it.
¡ Gone means that view is not present and so we can not see it.
Example :
android:visibility="visible"
write the below code in activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frame" Otuput
android:layout_width="200dp"
android:layout_height="300dp"
tools:context=".MainActivity">

<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:visibility="invisible"
android:textSize="20sp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:background="@color/colorPrimary"
android:textColor="#fff"
android:text="I am TextView" />

</FrameLayout>
You can see that Textview is present (blue border rectangle) but we can not see it.

5. android:measureAllChildren :
· This determines whether to measure all children including gone state visibility or just those which are
in the visible or invisible state of measuring visibility.
· The default value of measureallchildren is false. We can set values in the form of Boolean i.e. "true"
OR "false".
· This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in
the form "?[package:][type:]name") containing a value of this type.
· If measureallchildren is set true then it will show actual width and height of frame layout even if the
views visibility is in gone state.
Example : To set the ImageView visibility to gone and measureAllChildren to true.
activity_main.xml
Note: Make sure you have image in Drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:orientation="vertical" android:layout_width="wrap_content"

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 40 Components and Layouts

android:layout_height="wrap_content"
android:measureAllChildren="true"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:src="@drawable/ic_launcher"/>

</FrameLayout>
code of MainActivity.java . Here we have used Toast to display height and width on screen.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
FrameLayout frame=(FrameLayout)findViewById(R.id.frame);
frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = frame.getMeasuredWidth();
int height = frame.getMeasuredHeight();
Toast.makeText(getApplicationContext(),"width="+width+" height="+height,Toast.LENGTH_SHORT).show();
}
}
Otuput

Explanation of Example : It measures all the children in the layout. For ex: If we setVisiblity of an
view be gone and set measuresAllChildren property to be true, then also it will also count to that view
which is not visible, but if we set the measuresAllChildren property to be false, then it will not count
to that view which is gone.
Example 1 : Frame Layout using layout gravity. Here we will put textview at different position in
Frame Layout. Below is the code and final output :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 41 Components and Layouts

<TextView android:text="LeftTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightTop"
android:layout_gravity="top|right" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CentreTop"
android:layout_gravity="top|center_horizontal" />
<TextView android:text="Left"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Right"
android:layout_gravity="right|center_vertical" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Centre"
android:layout_gravity="center" />
<TextView android:text="LeftBottom"
android:layout_gravity="left|bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightBottom"
android:layout_gravity="right|bottom" />
<TextView android:layout_height="wrap_content" Output
android:layout_width="wrap_content"
android:text="CenterBottom"
android:layout_gravity="center|bottom" />
</FrameLayout>
Step 3 : Let the MainActivity.java has default Android code or
add the below code :
packagevrs.com.A12;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 42 Components and Layouts

Example :
activity_main.xml

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


<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/garden" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#4C374A"
android:padding="10dp"
android:text="My Garden"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>
Here we used ImageView to show the image (garden) from drawable folder in framelayout. So add
your image to drawable folder and replace @drawable/garden path with your image path.

open main activity file MainActivity.java from \java\com.vrs.framelayout path and write the code like
as shown below.
MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 43 Components and Layouts

super.onCreate(savedInstanceState); 4. setForegroundGravity(int foregroundGravity) :


setContentView(R.layout.activity_main); Describes how the foreground is positioned.
}
5. setMeasureAllChildren(boolean measureAll) :
}
Sets whether to consider all children, or just
Output those in the VISIBLE or INVISIBLE state, when
measuring.
6. shouldDelayChildPressedState() : Return true if
the pressed state should be delayed for children
or descendants of this ViewGroup.
7. generateDefaultLayoutParams() : Returns a set of
layout parameters with a width of
ViewGroup.LayoutParams.MATCH_PARENT,
and a height
ViewGroup.LayoutParams.MATCH_PARENT.
8. generateLayoutParams(ViewGroup.LayoutParams
lp) : Returns a safe set of layout parameters
based on the supplied layout params.
9. onLayout(boolean changed, int left, int top, int
right, int bottom) : Called from layout when this
view should assign a size and position to each of
its children.
10. onMeasure(int widthMeasureSpec, int
heightMeasureSpec) : Measure the view and its
content to determine the measured width and the
measured height. This method is invoked by
measure(int, int) and should be overridden by
sub classes to provide accurate and efficient
Methods of FrameLayout :
measurement of their contents.
To control the framelayout from JAVA class, android
gives us the following in-built methods to use. 3.3.4 Android Table Layout
1. generateLayoutParams(AttributeSet attrs) : It
Returns a new set of layout parameters based on Table layout
the supplied attributes set.
Table row n
2. getAccessibilityClassName() : Return the class View n
name of this object to be used for accessibility
purposes.
Table row m
3. getMeasureAllChildren() : · Determines whether View m
all children, or just those in the VISIBLE or
INVISIBLE state, are considered when measuring.
· It will return boolean value. (True or False) Fig. 3.3.7 Table layout
· If it returns false then compiler will consider · The TableLayout is used for arranging the enclosed
only VISIBLE or INVISIBLE state of children of controls into rows and columns.
framelayout.
· Each new row in the TableLayout is defined
· For true, it will consider VISIBLE, INVISIBLE through a TableRow object.
and GONE state of children of framelayout.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 44 Components and Layouts

· A row can have zero or more controls, where each control is called a cell.
· The number of columns in a TableLayout is determined by the maximum number of cells in any row.
· The width of a column is equal to the widest cell in that column. All elements are aligned in a
column; that is, the width of all the controls increases if the width of any control in the column is
increased.
· Table Layout containers do not display a border line for their columns, rows or cells. A Table will
have as many columns as the row with the most cells.
· TableLayout is a ViewGroup subclass which is used to display the child View elements in rows and
columns.
· TableLayout will position its children elements into
Row 1 Row 1 Row 1
rows and columns and it won't display any border Column 1 Column 2 Column 3
lines for rows, columns or cells.
Row 2 Row 2
· The TableLayout in android will work same as Column 1 Column 2
HTML table and table will have as many columns as
Row 3
the row with the most cells. The TableLayout can be Column 1
explained as <table> and TableRow is like <tr>
Fig. 3.3.8 Row and Column in Table Layout Android
element.

Important Points About Table Layout In Android :


· For building a row in a table we will use the <TableRow> element. Table row objects are the child
views of a table layout.
· Each row of the table has zero or more cells and each cell can hold only one view object like
ImageView, TextView or any other view.
· Total width of a table is defined by its parent container
· Column can be both stretchable and shrinkable. If shrinkable then the width of column can be shrunk
to fit the table into its parent object and if stretchable then it can expand in width to fit any extra
space available.
· We cannot specify the width of the children's of the Table layout. Here, width always match parent
width. However, the height attribute can be defined by a child; default value of height attribute is
wrap content.

Basic Table Layout code in XML :


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row-->

<!-- first row of the table layout-->


<TableRow
android:id="@+id/row1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- Add elements/columns in the first row-->


®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 45 Components and Layouts

</TableRow>
</TableLayout>

Attributes of table layout :

Attributes Where it is used Why it is used

android:stretchColumns TableLayout When a column width is less and you need to expand(or stretch) it,
you use this attribute.

android:shrinkColumns TableLayout When you do not need the extra space in a column, you can use
this attribute to shrink and remove the space.

android:collapseColumns TableLayout It hides the column of the given index in the TableLayout.

android:layout_span Any View inside If a view takes only one column width but when you want your
the TableRow view to take more than one column space, then you can use this
attribute.

android:layout_column Any view inside When you want your view present in the first TableRow to appear
the TableRow below the other TableRow's view, you can use this attribute.

1. id: id attribute is used to uniquely identify a Table Layout.


<TableLayout
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent/>
2. stretchColumns: · The default width of a column is set equal to the width of the widest column,
but we can stretch the column(s) to take up available free space using the android:stretchColumns
attribute in the TableLayout.
· The value assigned to this attribute can be a single column number or a comma-delimited list of
column numbers. The specified columns are stretched to take up any available space on the row.
· Stretch column attribute is used in Table Layout to change the default width of a column which is set
equal to the width of the widest column but we can also stretch the columns to take up available free
space by using this attribute.
· The value that assigned to this attribute can be a single column number or a comma delimited list of
column numbers (1, 2, 3…n).
· If the value is 1 then the second column is stretched to take up any available space in the row,
because of the column numbers are started from 0.
· If the value is 0,1 then both the first and second columns of table are stretched to take up the
available space in the row.
· If the value is '*' then all the columns are stretched to take up the available space.
Examples:
· android:stretchColumns="1" : The second column (because the column numbers are zero-based) is
stretched to take up any available space in the row.
· android:stretchColumns="0,1" : Both the first and second columns are stretched to take up the
available space in the row.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 46 Components and Layouts

· android:stretchColumns="*" : All columns are stretched to take up the available space.


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

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"> <!-- stretch the second column of the layout-->

<!-- first row of the table layout--> Output


<TableRow
1. whenandroid:stretchColumns="1"

android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- first element of the row-->


<TextView

android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" 2. whenandroid:stretchColumns="2"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Text 1"
android:textColor="#000"
android:textSize="12dp" />

<TextView

android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
3. whenandroid:stretchColumns="*"
android:layout_height="wrap_content"
android:background="#FF0000"
android:padding="18dip"
android:text="Text 2"
android:textColor="#000"
android:textSize="14dp" />

</TableRow>
</TableLayout>

1. shrinkColumns :
· We can shrink or reduce the width of the
column(s) using the android:shrinkColumns attribute in the TableLayout.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 47 Components and Layouts

· Shrink column attribute is used to shrink or reduce the width of the column's. We can specify either a
single column or a comma delimited list of column numbers for this attribute. The content in the
specified columns word-wraps to reduce their width.
· If the value is 0 then the first column's width shrinks or reduces by word wrapping its content.
· If the value is 0,1 then both first and second columns are shrinks or reduced by word wrapping its
content.
· If the value is '*' then the content of all columns is word wrapped to shrink their widths.
Examples :
· android:shrinkColumns="0": The first column's width shrinks or reduces by wordwrapping its
content.
· android:shrinkColumns="*" : The content of all columns is word-wrapped to shrink their widths.
Example :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="0"> <!-- shrink the first column of the layout-->

<!-- first row of the table layout-->


<TableRow
android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- first element of the first row-->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Shrink Column Example"
android:textColor="#000"
android:textSize="18dp" />

</TableRow>
</TableLayout>

2. collapseColumns :
· We can make the column(s) collapse or become invisible through the android:collapseColumns
attribute in the TableLayout.
· We can specify one or more comma-delimited columns for this attribute. These columns are part of
the table information but are invisible.
· We can also make column(s) visible and invisible through coding by passing the Boolean values false
and true , respectively, to the setColumnCollapsed() method in the TableLayout.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 48 Components and Layouts

For example:
· android:collapseColumns="0" :
¡ The first column appears collapsed; that is, it is part of the table but is invisible. It can be made
visible through coding by using the setColumnCollapsed() method.
¡ Collapse columns attribute is used to collapse or invisible the column's of a table layout. These
columns are the part of the table information but are invisible.
¡ If the values is 0 then the first column appears collapsed, i.e it is the part of table but it is invisible.
Example :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row-->

<!-- first row of the table layout-->


<TableRow
android:id="@+id/simpleTableLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<!-- first element of the row that is the part of table but it is invisible-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 1"
android:textColor="#000"
android:textSize="18dp" />

<!-- second element of the row that is shown in the screenshot-->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 2"
android:textColor="#000"
android:textSize="18dp" />
</TableRow>
</TableLayout>

Android TableLayout Example1


activity_main.xml

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


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 49 Components and Layouts

android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TableRow android:background="#0079D6" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Abhi" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pune" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 50 Components and Layouts

android:text="Rohit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nasik" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content" Output
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Jaya" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nasik" />
</TableRow>
</TableLayout>

MainActivity.java
package com.vrs.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


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

Android TableLayout Example2


<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*" android:stretchColumns="*" android:background="#ffffff">

<!-- Row 1 with single column -->


<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 51 Components and Layouts

android:gravity="center_horizontal">

<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="18dp" android:text="Row 1" android:layout_span="3"
android:padding="18dip" android:background="#b0b0b0"
android:textColor="#000"/>

</TableRow>

<!-- Row 2 with 3 columns -->

<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 1"
android:layout_weight="1" android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 2"
android:layout_weight="1" android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 2 column 3"
android:layout_weight="1" android:background="#cac9c9"
android:textColor="#000000"
android:padding="20dip" android:gravity="center"/>
</TableRow>
<!-- Row 3 with 2 columns -->
<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 1"
android:layout_weight="1 android:background="#b0b0b0"
android:textColor="#000000"
android:padding="18dip" android:gravity="center"/>
<TextView
android:id="@+id/TextView04" android:text="Row 3 column 2"
android:layout_weight="1" android:background="#a09f9f"
android:textColor="#000000"
android:padding="18dip" android:gravity="center"/>
</TableRow>
</TableLayout>

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 52 Components and Layouts

Output 1. Center relative to Parent View. The attributes


used to set the location of the control relative to
a container are
· android:layout_alignParentTop - The top of the
control is set to align with the top of the
container.
· android:layout_alignParentBottom - The bottom
of the control is set to align with the bottom of
the container.
· android:layout_alignParentLeft - The left side
of the control is set to align with the left side of
3.3.5 Android Relative Layout the container.
Relative layout · android:layout_alignParentRight - The right
side of the control is set to align with the right
View 1
side of the container.
· android:layout_centerHorizontal - The control
is placed horizontally at the center of the
container.
View 2 View 3
· android:layout_centerVertical - The control is
placed vertically at the center of the container.
Fig. 3.3.9 Relative layout
· android:layout_centerInParent - The control is
· In RelativeLayout, each child element is laid out in
placed horizontally and vertically at the center
relation to other child elements; that is, the location
of the container
of a child element is specified in terms of the
desired distance from the existing children.
· In android, RelativeLayout is a ViewGroup which
is used to specify the position of child View
instances relative to each other (Child A to the left
of Child B) or relative to the parent (Aligned to the
top of parent).
· In android, RelativeLayout is very useful to design
user interface because by using relative layout we
can eliminate the nested view groups and keep our
layout hierarchy flat, which improves performance
of application.
· Following is the pictorial representation of relative
layout in android applications.
Common Attributes of RelativeLayout

When you want to place your Views in the center


relative to the parent, you can use the following 3
attributes :

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 53 Components and Layouts

1. android:layout_centerHorizontal="true" : This <!-- centerVertical example -->


places the view horizontally in the center of the <TextView
parent. As our parent view covers the whole android:layout_width="wrap_content"
screen of mobile therefore the view gets placed android:layout_height="wrap_content"
in the middle of the mobile screen horizontally. android:text="Text1 center vertical"
<!-- centerHorizontal example --> android:layout_centerVertical="true"
<TextView android:textSize="20sp"
android:layout_width="wrap_content" android:textColor="#000"
android:layout_height="wrap_content" />
android:text="Text1 center Horizontal" 3. android:layout_centerInParent="true" : This
android:layout_centerHorizontal="true" attribute will place the view in the center of the
android:textSize="20sp" parent. Since the parent in our example covers
android:textColor="#000" the whole screen of mobile, so the view gets
/> placed in the middle of the mobile screen, both
horizontally and vertically.
<!-- centerInParent example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center in parent"
android:layout_centerInParent="true"
android:textSize="20sp"
android:textColor="#000"
/>

2. android:layout_centerVertical="true" : This places


the view vertically in the center of the parent.
Since the parent view covers the whole screen of
mobile hence the view gets placed in the middle
of the mobile screen vertically.

2. Align by the parent view : These type of


attributes make the view act like a chewing gum
as it can be fixed to any side of the parent view
using these attributes.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 54 Components and Layouts

Again, for the example, we are considering our parent view to be a RelativeLayout with height and
width set as match_parent, therefore it will cover the whole screen of mobile. So the complete
screen is our parent view.
1. android:layout_alignParentTop="true" : If you write this attribute for a View, then that view will
stick to the top of its parent. Since the parent covers the whole screen of mobile therefore, the view
will appear sticking to the top-left of the mobile screen.
<!-- alignParentTop example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 align parent top"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:textSize="20sp"
android:textColor="#000"/>
2. android:layout_alignParentBottom="true" : If you write
this attribute for a View, then that view will stick to the bottom of its parent. Since the our parent
covers the whole screen of mobile therefore, the view will appear sticking to the bottom of the
mobile screen.
<!-- textView is alignParentBottom -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text Here is AlignParentBottom with bottom margin of 120dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="120dp" />
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 55 Components and Layouts

3. android:layout_alignParentLeft="true" : If you write this attribute for a View, then that view will
stick to the left of its parent. Since the parent in our example covers the whole screen of mobile
therefore, the view will appear sticking to the left of the mobile screen.
<!-- align parent left in Android -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Left"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentLeft="true"
/>
4. android:layout_alignParentRight="true" : If alignParentRight property is true, then it makes the
right edge of this view match the right edge of the parent. The value of align parent right is either
true or false. Example: android:layout_alignParentRight="true".
<!-- alignRightParent Example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Right"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentRight="true"
/>

3. Place new View relative to existing sibling View


· In a RelativeLayout you can keep(position) the new views relative to other existing views. Following
attributes can be used for doing so.
· Suppose there is one view in the center and its id is given as android:id="@+id/main" Therefore, the
other new views can be placed relative to this view as following :

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 56 Components and Layouts

1:android:layout_toLeftOf="@id/main"

2:android:layout_above="@id/main"

2 id=main 3

3:android:layout_below="@id/main"

4:android:layout_toRightOf="@id/main"

1. android:layout_toLeftOf="@id/main" : This tells the new view that you have to be on the left side
of the view whose id is main.
2. android:layout_toRightOf="@id/main" : This tells the
new view that you have to be on the right side of
a
the view whose id is main. b

3. android:layout_above="@id/main" : This tells the


android:layout_alignTop="@id/a"
new view that you have to be above the view whose
id is main.
a b
4. android:layout_below="@id/main" : This tells the
new view that you have to be below the view whose android:layout_alignBottom="@id/a"
id is main.
android:layout_alignLeft="@id/a"
Note : When you assign an id to the View, you write
android:id="@+id/main" i.e you write a + sign after the a a
@ symbol, indicating you are assigning an id to that
view. But when you use that id for other purpose, like
above, you are adding a new view relative to an b b

existing view having the specfied value of id, hence we


android:layout_alignRight="@id/d"
do not have to mention the + sign. We simply refer it as
android:layout_below="@id/main" i.e without the + sign. a
text1 text2
b
Align new View relative to existing sibling View
android:layout_alignBaseLine="@id/a"
If you want to align the new view relative to any
existing view, then you can use the following attributes.

1. android:layout_alignTop="@id/a" : This aligns the top margin of the new view with the top margin
of the view having id as a.
2. android:layout_alignBottom="@id/a" : This aligns the bottom margin of the new view with the
bottom margin of the view having id as a.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 57 Components and Layouts

3. android:layout_alignLeft="@id/a" : This aligns the left margin of the new view with the left margin
of the view having id as a.
4. android:layout_alignRight="@id/a" : This aligns the right margin of the new view with the right
margin of the view having id as a.
5. android:layout_alignBaseLine="@id/a" : This aligns the text1 of the new view with the text2 of the
view having id as a.

4. above :
· android:layout_above - The control is placed above the referenced control.
Position the bottom edge of the view above the given anchor view ID and must be a reference of the
another resource in the form of id. Example, android:layout_above="@+id/textView" .
For example, suppose a view with id textview2 is what we want to place above another view with id
textview.
<!-- textView2 is placed above textView-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Text2"
android:id="@+id/textView2"
android:layout_above="@+id/textView"
android:layout_marginBottom="100dp"
android:layout_centerHorizontal="true"/>

· The attributes to control the position of a control in relation to other controls are
· android:layout_below - The control is placed below the referenced control.
· android:layout_toLeftOf - The control is placed to the left of the referenced control.
· android:layout_toRightOf - The control is placed to the right of the referenced control.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 58 Components and Layouts

5. alignBottom :
· android:layout_alignBottom - The bottom of the control is set to align with the bottom of the
referenced control.
alignBottom is used to makes the bottom edge of the view match the bottom edge of the given anchor
view ID and it must be a reference to another resource, in the form of id. Example: android:layout_
alignBottom ="@+id/button1?
For example align a view with id textView2 Bottom of another view with id textView..
<!-- textView2 alignBottom of textView -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerHorizontal="true"
android:id="@+id/textView2"
android:layout_alignBottom="@+id/textView"
android:text="Text2 alignBottom of Text1"
android:layout_marginBottom="90dp"
/>

6. alignLeft :
· android:layout_alignLeft - The left side of the control is set to align with the left side of the
referenced control.
alignLeft is used to make the left edge of the view match the left edge of the given anchor view ID
and must be a reference to another resource, in the form of Example: android:layout_ alignLeft
="@+id/button1?.
For example align a view with id textView2 left of another view with id textView.
<!-- textView2 alignLeft of textView -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:text="Text2 alignLeft of Text1"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 59 Components and Layouts

android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>

7. alignRight :
· android:layout_alignRight - The right side of the control is set to align with the right side of the
referenced control.
alignRight property is used to make the right edge of this view match the right edge of the given
anchor view ID and must be a reference to another resource, in the form like this example:
android:layout_alignRight="@+id/button1?
For example align a view with id textView2 right of another view with id textView.
<!-- textView2 alignRight of textView-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignRight="@+id/textView"
android:text="Text2 alignRight of Text1"
android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>

8. alignStart :
· alignStart property is used to makes the start edge of this view match the start edge of the given
anchor view ID and must be a reference to another resource, in the form of like this example:
android:layout_alignStart="@+id/button1?
For example align a view with id textView2 start of another view with id textView.
<!-- Text2 alignStart-->
<TextView
android:layout_width="wrap_content"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 60 Components and Layouts

android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:text="Text2 align start of Text1"
android:layout_alignStart="@+id/textView"
/>

9. alignTop :
· android:layout_alignTop - The top of the control is set to align with the top of the referenced control.
alignTop property is used to makes the top edge of this view match the top edge of the given anchor
view ID and must be a reference to another resource, in the form like this example:
android:layout_alignTop="@+id/button1?.
For example align a view with id textView Top of another image with id imageView.
<!--text is align top on Image-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignTop="@+id/imageView"
android:text="Text Here is AlignTop on Image"
/>

10. alignParentEnd : If alignParentEnd property is true, then it makes the end edge of this view match
the end edge of the parent. The value of align parent End is either true or false. Example:
android:layout_alignParentEnd="true".
For example textView is simply displayed on Image in the end.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 61 Components and Layouts

<!-- Text displayed in the end of parent image-->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent End"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentEnd="true"
/>

11. alignParentStart: If alignParentStart is true, then it makes the start edge of this view match the
start edge of the parent. The value of align parent start is either true or false. Example:
android:layout_alignParentStart="true".
For example textView is simply displayed on parent Image in the right side.
<!-- alignParentStart Example -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:text="Text in Parent Start"
android:layout_alignTop="@+id/imageView"
android:layout_alignParentStart="true"
/>
12. For spacing, Android defines two attributes: android:layout_margin and android:padding .
· The android:layout_margin attribute defines spacing for the container, while android:padding
defines the spacing for the view. Let's begin with padding.
· android:padding - Defines the spacing of the content on all four sides of the control. To define
padding for each side individually, use android:paddingLeft ,android:paddingRight ,
android:paddingTop , and android:paddingBottom .
· android:paddingTop - Defines the spacing between the content and the top of the control.
· android:paddingBottom - Defines the spacing between the content and the bottom of the control.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 62 Components and Layouts

· android:paddingLeft - Defines the spacing between the content and the left side of the control.
· android:paddingRight - Defines the spacing between the content and the right side of the control.
13. Here are the attributes that define the spacing between the control and the container:
· android:layout_margin - Defines the spacing of the control in relation to the controls or the
container on all four sides. To define spacing for each side individually, we use the
android:layout_marginLeft , android:layout_marginRight , android:layout_marginTop , and
android:layout_marginBottom options.
· android:layout_marginTop - Defines the spacing between the top of the control and the related
control or container.
· android:layout_marginBottom - Defines the spacing between the bottom of the control and the
related control or container.
· android:layout_marginRight - Defines the spacing between the right side of the control and the
related control or container.
· android:layout_marginLeft - Defines the spacing between the left side of the control and the related
control or container.
Example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />

<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 63 Components and Layouts

android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
<Button Output
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button7" />
</RelativeLayout>
MainActivity.java
package com.vrs.relativelayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Example :
activity_relative_layout_android_example.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".RelativeLayoutAndroidExample" >

<TextView
android:id="@+id/text1"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 64 Components and Layouts

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="false"
android:text="LOGIN"
android:layout_marginTop="14dp"
android:textAppearance="?android:attr/textAppearanceLarge"
/>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text1"
android:layout_marginTop="20dp"
android:text="Username :"
android:textAppearance="?android:attr/textAppearanceLarge" />
Output
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_toRightOf="@+id/textView1"
/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="20dp"

android:text="Password :"
android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView2"
android:layout_toRightOf="@+id/textView2"
android:inputType="textPassword"
/>

<Button
android:id="@+id/btnSubmit"

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 65 Components and Layouts

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_below="@+id/editText2"
android:layout_centerInParent="true"
android:text="Submit" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="SIGNUP"
android:layout_centerHorizontal="true"/>

</RelativeLayout>

Difference between Linear And Relative Layout :

Relative Layout :
· Every element of relative layout arranges itself to the other element or a parent element.
· It is helpful while adding views one next to other etc
· In a relative layout you can give each child a Layout Property that specifies exactly where it should
go in relative to the parent or relative to other children.
· Views can be layered on top of each other.

Linear Layout :
· In a linear layout, like the name suggests, all the elements are displayed in a linear fashion either
vertically or horizontally.
· Either Horizontally or Vertically this behavior is set in android:orientation which is an property of the
node Linear Layout.
android:orientation="horizontal" or android:orientation="vertical"
· Linear layouts put every child, one after the other, in a line, either horizontally or vertically.

qqq

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 3 - 66 Components and Layouts

Notes

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - IV

4
4.1 The Android View
Designing User Interface with View

· It represents a rectangular portion of the screen. The


View class serves as the base class for nearly all the
· GUI components are all types of views-behind the
user interface controls and layouts within the
scenes, they are all subclasses of the
Android SDK.
study.view.View class.
· A view is a widget that has an appearance on
· This means that all of the GUI components in your
screen. It is derived from the base class
user interface have attributes and behavior in
study.view.View.
common.
· There are three types :
· They can all be displayed on the screen, for
instance, and you get to say how tall or wide they 1. Basic views - Commonly used views, such as
should be. Each of the GUI components you use in the TextView, Edit Text, and Button views
your user interface takes this basic functionality and 2. Picker views - Views that enable users to select
extends it. from a list, such as the TimePicker and
· The Android SDK has a Java package named DatePicker views
study.view. 3. List views - Views that display a long list of
· This package contains a number of interfaces and items, such as the ListView and the
classes related to drawing on the screen. SpinnerView views
· However, when we refer to the View object, we
4.1.1 Basic Views
actually refer to only one of the classes within this
package : the study.view.View class. Some of the basic views that can be used to design
UI of Android application are :
· The View class is the basic user interface building
· Text View : Text View is a user interface control
block within Android.
which is used to display the text to the user.

android.view.View is the base


class of all the GUI components
you use to develop your apps.
android.view.View
android.widget.TextView
is a direct subclass of the
View class. A spinner is a
type of View
android.widget.TextView android.widget.Spinner

android.widget.EditText android.widget.Button

Fig. 4.1.1 Hierarchy of view class

(4 - 1)® - An up thrust for knowledge


TECHNICAL PUBLICATIONS
Mobile Application Development 4-2 Designing User Interface with View

· Edit Text : Edit Text is a user interface control · Text View is a user interface control which is used
which is used to allow the user to enter or modify to display the text to the user.
the text.
android.view.View
· Android Auto Complete Text View : In android,
Auto Complete Text View is an editable text view
which is used to show the list of suggestions based
on the user typing text. The list of suggestions will android.widget.TextView
be shown as a dropdown menu from which the
user can choose an item to replace the content of
Fig. 4.1.2 Text view
textbox.
4.1.1.2 Declare UI Elements in XML
· Button : Button is a user interface control which is
used to perform an action when the user click or When you create a new Android project, Android
tap on it. Studio always creates the act_ex.xml file which
contains a <TextView> element:
· Image Button : Image Button is a user interface
<?xml version="1.0" encoding="utf-8"?>
control which is used to display a button with
<LinearLayout xmlns:study="url"
image to perform an action when user click or tap
study:orientation="vertical"
on it. Generally, the Image button in android looks
study:layout_width="match_pr"
similar as regular Button and perform the actions
study:layout_height="match_pr">
same as regular button but only difference is for
<TextView
image button we will add an image instead of text.
study:id="@+id/fstTxt"
· Check Box : Checkbox is a two states button that study:layout_width="wrap_cnt"
can be either checked or unchecked. study:layout_height="wrap_cnt"
· Toggle Button : Toggle Button is a user interface study:text="Enter your account number" />
control which is used to display ON (Checked) or </LinearLayout>
OFF (Unchecked) states as a button with a light
4.1.2 Edit Text
indicator.
· A Edit Text is an overlay over Text View that
· Radio Button : Radio Button is a two states button
configures itself to be editable.
that can be either checked or unchecked and it
cannot be unchecked once it is checked. · It is the predefined subclass of Text View that
includes rich editing capabilities.
· Radio Group : Radio Group is used to group one or
more radio buttons into separate groups based on android.view.View
our requirements. In case if we group radio buttons
using radio group, at a time only one item can be
selected from the group of radio buttons.
android.widget.TextView
4.1.1.1 Text View
· In android, Text View is a user interface control
which is used to set and display the text to the user
android.widget.EditText
based on our requirements.
· The Text View control will act as like label control
and it won't allow users to edit the text. Fig. 4.1.3 Edit text view

· In android, we can create a Text View control in · In Android, Edit Text is a standard entry widget in
two ways either in XML layout file or create it in android apps.
Activity file programmatically. · It is an overlay over Text View that configures itself
to be editable.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-3 Designing User Interface with View

· Edit Text is a subclass of Text View with text editing operations.


· We often use Edit Text in our applications in order to provide an input or text field, especially in
forms.
· A Edit Text is an overlay over Text View that configures itself to be editable.
· It is the predefined subclass of Text View that includes rich editing capabilities.
· Edit Text is a user interface control which is used to allow the user to enter or modify the text.
· Example : Modifying the Main.axml to see the effect of autoText, capitalize and password properties
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:study="url"
study:orientation="vertical"
study:layout_width="fill_pr"
study:layout_height="fill_pr"
>
<Edit Text
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:capitalize="characters"
study:autoText="true"
/>
<Edit Text
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:capitalize="words"
study:autoText="true"
/>
<Edit Text
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:capitalize="none"
study:autoText="true"
/>
<Edit Text
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:password="true"
/>
</LinearLayout>
In android, we can create Edit Text control in two ways

1. In XML layout file


2. Create it in Activity file programmatically.

Android Edit Text Attributes


Following are the some of commonly used attributes related to Edit Text control in android
applications.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-4 Designing User Interface with View

1. Id : id is an attribute used to uniquely identify a text Edit Text. Below is the example code in
which we set the id of a edit text.
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_height="wrap_cnt"
study:layout_width="match_pr"/>
2. Gravity : The gravity attribute is an optional attribute which is used to control the alignment of the
text like left, right, center, top, bottom, center_vertical, center_horizontal etc.
For example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:text="Enter Name"
study:gravity="left"/>
3. Text : text attribute is used to set the text in a Edit Text. We can set the text in xml as well as in
the java class.
Setting the text in xml
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Subject"/>
Setting text in Edit Text In Java class :
example
Edit Text Edit Text = (Edit Text)findViewById(R.id.simpleEdit Text);
Edit Text.setText("Subject");
4. TextColor : textColor attribute is used to set the text color of a text edit text. Color value is in the
form of "#argb", "#rgb", "#rrggbb", or "#aarrggbb".
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Name"
study:textColor="#00ff00"/>
Setting textColor in Edit Text In Java class:
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setTextColor(Color.GREEN);
5. TextColorHint : textColorHint is an attribute used to set the color of displayed hint.
example.
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-5 Designing User Interface with View

study:layout_centerInParent="true"
study:hint="Username"
study:textColorHint="#0f0"/>
Setting textColorHint in Edit Text In Java class :
example
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setHintTextColor(Color.green(0))
6. Hint : hint is an attribute used to set the hint i.e. what you want user to enter in this edit text.
Whenever user start to type in edit text the hint will automatically disappear.
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:hint="Email_id" />
Setting hint in Edit Text In Java class:
Edit Text Edit Text = (Edit Text)findViewById(R.id.simpleEdit Text);
Edit Text.setHint("Email_id");
7. Background : background attribute is used to set the background of a edit text. We can set a color
or a drawable in the background of a edit text.
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:textColorHint="#fff"
study:textStyle="bold|italic"
study:layout_centerInParent="true"
study:hint="Enter Email_id "
study:padding="20dp"
study:background="#0f0"/>
Setting Background in Edit Text In Java class :
Below is the example code in which we set the background color of a edit text programmatically
means in java class.
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setBackgroundColor(Color.GREEN);
8. Padding : padding attribute is used to set the padding from left, right, top or bottom.
9. TextSize : textSize attribute is used to set the size of text of a edit text. We can set the text size in
sp(scale independent pixel) or dp(density pixel).
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Password"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-6 Designing User Interface with View

study:textSize="35sp" />
Setting textSize in Edit Text in Java class :
example
Edit Text simpleEdit Text=(Edit Text)findViewById(R.id.simpleEdit Text);
simpleEdit Text.setTextSize(35);//
10. TextStyle : textStyle attribute is used to set the text style of a edit text. The possible text styles are
bold, italic and normal. If we need to use two or more styles for a edit text then "|" operator is
used for that.
example
<Edit Text
study:id="@+id/simpleEdit Text"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_centerInParent="true"
study:text="Email"
study:textSize="25sp"
study:textStyle="bold|italic"/>

4.1.3 Button
· Button, as understood by its name, is a component which can be pressed or clicked by the user to
perform an action.
· It has the same properties as a Text View, with a few Button specific properties.
· Button, as understood by its name, is a component which can be pressed or clicked by the user to
perform an action.
· It has the same properties as a Text View, with a few Button specific properties.
· Button is a user interface control which is used to perform an action when the user click or tap on it.
· The main usage of the Button view is that whenever we click a button, we can set a method that will
handle that specific button request and will carry out the necessary action.
· This can be done inside the Activity class as following:
· Buttons are usually used to make your app do something when they're clicked.
· Android buttons are Android GUI components which are sensible to taps (clicks) by the user. When
the user taps an Android button in an Android app, the app can respond to the tap.
· Android buttons can be divided into two categories.
¡ Buttons with text on
¡ Buttons with an image on
¡ Buttons with images on can contain both an image and a text.
· Android buttons with images on are also called image buttons..

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-7 Designing User Interface with View

4.1.3.1 Button Attributes 5. gravity : The gravity attribute is an optional


attribute which is used to control the alignment
android.view.View of the text like left, right, center, top, bottom,
center_vertical, center_horizontal etc.
6. textColor : textColor attribute is used to set the
android.widget.TextView
text color of a Button.
7. padding : padding attribute is used to set the
padding from left, right, top or bottom. In above
example code of background we also set the
android.widget.Button
10dp padding from all the side's of button.
8. drawableBottom : drawableBottom is the
Fig. 4.1.4 Button attributes drawable to be drawn to the below of the text.

· Button is a subclass of TextView and inherits 9. drawableTop, drawableRight And drawableLeft :


attributes from TextView and View classes. Below Just like the above attribute we can draw
are some of the important button attributes which drawable to the left, right or top of text.
can be used to defined desired button look and
4.1.4 Image Button
behavior.
· An Image Button is an Absolute Layout which
· Example :
enables you to specify the exact location of its
<Button
children.
study:id="@+id/simpleButton"
study:layout_width="fill_pr" · This shows a button with an image (instead of text)
study:layout_height="wrap_cnt" that can be pressed or clicked by the user.
study:layout_centerInParent="true" · An Image Button is an Absolute Layout which
study:text="Download" enables you to specify the exact location of its
study:textSize="25sp" children.
study:padding="14dp"
· This shows a button with an image (instead of text)
study:gravity="right|center_vertical"
that can be pressed or clicked by the user.
study:textStyle="bold|italic"
study:background="#5b39c6" · Image Button is a user interface control which is
study:textColor="#0f0"/> used to display a button with image to perform an
Attributes of button mentioned in above example action when user click or tap on it.
are :
android.view.View
1. id : id is an attribute used to uniquely identify a
text Button. Below is the example code in which
we set the id of a Button.
android.widget.ImageView
2. background : background attribute is used to set
the background of a Button.
3. textSize : textSize attribute is used to set the size
of the text on Button. The text size in sp(scale android.widget.ImageButton
independent pixel) or dp(density pixel).
4. textStyle : textStyle attribute is used to set the
text style of a Button. The possible text styles are The ImageButton class
extends the ImageView class,
bold, italic and normal. If we need to use two or
not the Button class.
more styles for a Button then "|" operator is used
for that. Fig. 4.1.5 Image button layout
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-8 Designing User Interface with View

· Generally, the Image button in android looks similar as regular Button and perform the actions same
as regular button but only difference is for image button we will add an image instead of text.
· An image button is just like a button, except it contains an image and no text.
· In simple words we can say, Image Button is a button with an image that can be pressed or clicked
by the users.
· The Image Button component is a button with an image on. The Image Button is represented by the
Android class study.widget.ImageButton .

4.1.4.1 Image Button Attributes


1. id : id is an attribute used to uniquely identify a image button. Below is the example code in
which we set the id of a image button.
2. src : src is an attribute used to set a source file of image or you can say image in your image
button to make your layout look attractive.
Setting Image Source In ImageButton Using Java class :
We can also set the source image at run time programmatically in java class. For that we use
setImageResource() function as shown in below example code.
/*Add in Oncreate() funtion after setContentView()*/

ImageButton simpleImageButton = (ImageButton)findViewById(R.id.simpleImageButton);


simpleImageButton.setImageResource(R.drawable. button_icon); //set the image programmatically
3. background : background attribute is used to set the background of an image button. We can set a
color or a drawable in the background of a Button.
Setting Background In ImageButton Using Java class :
Below is the example code in which we set the black background color of a image button
programmatically means in java class.
/*Add in Oncreate() funtion after setContentView()*/
ImageButton simpleImageButton = (ImageButton) findViewById(R.id.simpleImageButton);
simpleImageButton.setBackgroundColor(Color.BLACK); //set black background color for image button
4. padding : padding attribute is used to set the padding from left, right, top or bottom of the
ImageButton.
· paddingRight : Set the padding from the right side of the image button.
· paddingLeft : Set the padding from the left side of the image button.
· paddingTop : Set the padding from the top side of the image button.
· paddingBottom : Set the padding from the bottom side of the image button.
· padding : Set the padding from the all side's of the image button.

4.1.5 Toggle Button


· In android, Toggle Button is a user interface control which is used to display ON (Checked) or OFF
(Unchecked) states as a button with a light indicator.
· The Toggle Button is useful for the users to change the settings between two states either ON or OFF.
· In Android, Switch is a two-state toggle switch widget that can select between two options.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4-9 Designing User Interface with View

· It is used to display checked and unchecked state android.view.View


of a button providing slider control to user.
Switch is a subclass of Compound Button.
· Toggle Button is a user interface control which is android.widget.TextView
used to display ON (Checked) or OFF
(Unchecked) states as a button with a light
indicator.
android.widget.Button
· A toggle button allows you to choose between
two states by clicking a button.
A compound button
· In android, Toggle Button is a user interface is a button with two
android.widget.
states, checked and
control which is used to display ON (Checked) or CompoundButton
unchecked. A toggle
OFF (Unchecked) states as a button with a light button is an implementation
of a compound button.
indicator.
· The Toggle Button is useful for the users to android.widget.
change the settings between two states either ON ToggleButton

or OFF. We can add a Toggle Button to our


application layout by using Toggle Button object.
Fig. 4.1.6 Toggle button layout
· By default, the android ToggleButton will be in
OFF (Unchecked) state. We can change the default state of ToggleButton by using study : checked
attribute.

Create Toggle Button in XML Layout File


Following is the sample way to define ToggleButton control in XML layout file in android application.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:study="url"
study:layout_width="match_pr" study:layout_height="match_pr">
<ToggleButton
study:id="@+id/toggle1"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:layout_marginLeft="100dp"
study:layout_marginTop="120dp"
study:checked="true"
study:textOff="OFF"
study:textOn="ON"/>
</RelativeLayout>
If you observe above code snippet, ToggleButton control and setting ToggleButton state ON using
study:checked attribute in xml layout file.

Create ToggleButton Control in Activity File


In android, we can create ToggleButton control programmatically in activity file based on requirements.

Following is the example of creating ToggleButton control dynamically in activity file.


RelativeLayout layout = (RelativeLayout)findViewById(R.id.r_layout);
ToggleButton tb = new ToggleButton(this);
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 10 Designing User Interface with View

tb.setTextOff("OFF");
tb.setTextOn("ON");
tb.setChecked(true);
layout.addView(tb);
This shows ToggleButton in XML layout file or programmatically in activity file based on our
requirements.

Android ToggleButton Control Attributes


Following are the some of commonly used attributes related to ToggleButton control in android
applications.
<ToggleButton
study:id="@+id/simpleToggleButton"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:checked="true"
study:textOff="Off State"
study:textOn="On State"
study:layout_centerHorizontal="true"
study:textColor="#000"
study:drawableTop="@drawable/switch" />
1. id : id is an attribute used to uniquely identify a toggle button.
2. checked : checked is an attribute of toggle button used to set the current state of a toggle button.
The value should be true or false where true shows the checked state and false shows unchecked
state of a toggle button. The default value of checked attribute is false. We can also set the current
state programmatically.
Setting Checked Of ToogleButton Current State In Java Class :
Below we set the current state of toggle button to checked :
/*Add in Oncreate() funtion after setContentView()*/
ToggleButton simpleToggleButton = (ToggleButton) findViewById(R.id.simpleToggleButton); // initiate a
toggle button
simpleToggleButton.setChecked(true); // set the current state of a toggle button
3. gravity : The gravity attribute is an optional attribute which is used to control the alignment of the
text in ToogleButton like left, right, center, top, bottom, center_vertical, center_horizontal etc.
4. textOn And textOff : textOn attribute is used to set the text when toggle button is in checked/on
state.
Setting textOn and textOff Of ToggleButton In Java class :
/*Add in Oncreate() funtion after setContentView()*/
// initiate toggle button
ToggleButton simpleToggleButton = (ToggleButton) findViewById(R.id.simpleToggleButton);
// displayed text of the toggle button whenever it is in checked or on state
simpleToggleButton.setTextOn("TextOn Attribute Of Toggle b3`utton");
// displayed text of the toggle button whenever it is in unchecked or off state
simpleToggleButton.setTextOff("TextOff Attribute Of Toggle b3`utton");
5. textColor : textColor attribute is used to set the text color of a toggle button. Color value is in the
form of "#argb", "#rgb", "#rrggbb", or "#aarrggbb".

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 11 Designing User Interface with View

Setting textColor Of ToggleButton In Java class :


/*Add in Oncreate() funtion after setContentView()*/
ToggleButton simpleToggleButton = (ToggleButton) findViewById(R.id.simpleToggleButton);// initiate toggle
button simpleToggleButton.setTextColor(Color.RED); //red color for displayed text of toggle button
6. textSize : textSize attribute set the size of the text of a toggle button. We can set the text size in
sp(scale independent pixel) or dp(density pixel).
Setting textSize Of ToggleButton Text In Java class:
/*Add in Oncreate() funtion after setContentView()*/
ToggleButton simpleToggleButton = (ToggleButton) findViewById(R.id.simpleToggleButton); // initiate toggle
button
simpleToggleButton.setTextSize(25); // set 25sp displayed text size of toggle button
7. textStyle : textStyle attribute is used to set the text style of the text of a Toggle button. You can set
bold, italic and normal. If you need to use two or more styles for a text view then "|" operator is
used for that.
8. background : background attribute is used to set the background of a toggle button. We can set a
color or a drawable in the background of a toggle button.
Setting Background Of ToggleButton Text In Java class:
/*Add in Oncreate() funtion after setContentView()*/
ToggleButton simpleToggleButton = (ToggleButton) findViewById(R.id.simpleToggleButton);
simpleToggleButton.setBackgroundColor(Color.BLACK);
9. padding : padding attribute is used to set the padding from left, right, top or bottom.
· paddingRight : Set the padding from the right side of the toggle button.
· paddingLeft : Set the padding from the left side of the toggle button.
· paddingTop : set the padding from the top side of the toggle button.
· paddingBottom : Set the padding from the bottom side of the toggle button.
· Padding : set the padding from the all side's of the toggle button.
10. drawableBottom, drawableTop, drawableRight And drawableLeft : These attribute draw the
drawable below, top, right and left of the text of ToggleButton.
Android ToggleButton Example
Drag two toggle button and one button for the layout. Now the act_ex.xml file will look like this :
<?xml version="1.0" encoding="utf-8"?>
<study.support.constraint.ConstraintLayout xmlns:study="url"
xmlns:app="ex.//url/apk/res-auto"
xmlns:tools="url"
study:layout_width="match_pr"
study:layout_height="match_pr"
tools:context="url">
<ToggleButton
study:id="@+id/toggleButton"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:layout_marginLeft="8dp"
study:layout_marginTop="80dp"
study:text="ToggleButton"
study:textOff="Off"
study:textOn="On"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 12 Designing User Interface with View

app:layout_constraintEnd_toStartOf="@+id/toggleButton2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ToggleButton
study:id="@+id/toggleButton2"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:layout_marginRight="60dp"
study:layout_marginTop="80dp"
study:text="ToggleButton"
study:textOff="Off"
study:textOn="On"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
study:id="@+id/button"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:layout_marginBottom="144dp"
study:layout_marginLeft="148dp"
study:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</study.support.constraint.ConstraintLayout>
Let's write the code to check which toggle button is ON/OFF.
package example.url.togglebutton;
import study.support.AppCompatActivity;
import study.os.Bundle;
import study.view.View;
import study.widget.Button;
import study.widget.Toast;
import study.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private ToggleButton toggleButton1, toggleButton2;
private Button buttonSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button);
//Performing action on button click
buttonSubmit.setOnClickListener(new View.OnClickListener(){
@Override

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 13 Designing User Interface with View

public void onClick(View view) {


StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(toggleButton1.getText());
result.append("\nToggleButton2 : ").append(toggleButton2.getText());
//Displaying the message in toast
Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show();
}
});
}
}

4.1.6 Radio Button


· A radio button is a form element that allows the user to select one option from a range of options.
Radio buttons are created with the HTML <input> tag.
· Radio buttons can be nested inside a <form> element or they can stand alone.
· They can also be associated with a form via the
form attribute of the <input> tag. Use radio buttons to
Tea Coffee restrict the user's
· Radio Button is a two states button that can be choice to just one option.
either checked or unchecked and it cannot be
unchecked once it is checked. Fig. 4.1.7 Radio button

· These let you display multiple options to the


android.view.View
user. The user can select a single option.
· Radio Buttons are used when you want to
allow only one choice from a list of possible
android.widget.TextView
choices. For example, you might ask users to
choose tea or coffee. Out of those two choices,
the user can only select one.
android.widget.Button
· Radio Button is a two states button which is
either checked or unchecked.
· If a single radio button is unchecked, we can
android.widget.
click it to make checked radio button. Once a CompoundButton
radio button is checked, it cannot be marked as
unchecked by user.
· Radio Button is generally used with
android.widget.
RadioGroup. RadioButton
· Radio Group contains several radio buttons,
marking one radio button as checked makes all
Fig. 4.1.8 Radio button layout
other radio buttons as unchecked.
Example
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 14 Designing User Interface with View

Male Female

Attributes of radio button In study :


1. id : id is an attribute used to uniquely identify a radio button.
2. checked : checked attribute in radio button is used to set the current state of a radio button. We
can set it either true or false where true shows the checked state and false shows unchecked state
of a radio button. As usual default value of checked attribute is false. We can also set the current
state in JAVA.
Setting checked State Of Radio Button In Java Class:
Below code set the current state of Radio Button to checked programmatically.
/*Add in Oncreate() funtion after setContentView()*/
// initiate a radio button
RadioButton simpleRadioButton = (RadioButton) findViewById(R.id.simpleRadioButton);
// set the current state of a radio button
simpleRadioButton.setChecked(true);
3. text : text attribute is used to set the text in a radio button. We can set the text both ways either in
XML or in JAVA class.
Setting text of RadioButton In Java class :
/*Add in Oncreate() funtion after setContentView()*/
RadioButton simpleRadioButton=(RadioButton) findViewById(R.id.simpleRadioButton);
simpleRadioButton.setText("I am a radiobutton"); // displayed text of radio button
4. gravity : The gravity attribute is an optional attribute which is used to control the alignment of text
like left, right, center, top, bottom, center_vertical, center_horizontal etc.
5. textColor : textColor attribute is used to set the text color of a radio button. Color value is in the
form of "#argb", "#rgb", "#rrggbb", or "#aarrggbb".
Setting textColor of RadioButton text In Java class:
/*Add in Oncreate() funtion after setContentView()*/
RadioButton simpleRadioButton = (RadioButton) findViewById(R.id.simpleRadioButton);// initiate radio button
simpleRadioButton.setTextColor(Color.RED); //red color for displayed text of radio button
6. textSize : textSize attribute is used to set the size of the text of a radio button. We can set the text
size in sp(scale independent pixel) or dp(density pixel).
Setting textSize Of RadioButton Text In Java class:
/*Add in Oncreate() funtion after setContentView()*/
RadioButton simpleRadioButton = (RadioButton) findViewById(R.id.simpleRadioButton); // initiate radio
button
simpleRadioButton.setTextSize(25); // set 25sp displayed text size of radio button
7. textStyle : textStyle attribute is used to set the text style of the text of a radio button. The possible
text styles are bold, italic and normal. If we need to use two or more styles for a text view then "|"
operator is used for that.
8. background : background attribute is used to set the background of a radio button. We can set a
color or a drawable in the background of a radio button.
Setting background of radioButton in java class :
/*Add in Oncreate() funtion after setContentView()*/
RadioButton simpleRadioButton = (RadioButton) findViewById(R.id.simpleRadioButton);
simpleRadioButton.setBackgroundColor(Color.BLACK);

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 15 Designing User Interface with View

9. padding : padding attribute is used to set the 3. Enter your radio button items. ...
padding from left, right, top or bottom. 4. Click Add to add more item-value pairs to your
· paddingRight : Set the padding from the right list.
side of the radio button. 5. Click OK.
· paddingLeft : Set the padding from the left side of
Example for radio button :
the radio button.
In this example, we are going to implement single
· paddingTop : Set the padding from the top side of
radio button separately as well as radio button in
the radio button. RadioGroup.
· paddingBottom : Set the padding from the bottom ?xml version="1.0" encoding="utf-8"?>
side of the radio button. <LinearLayout
· Padding : Set the padding from the all side's of xmlns:study="url"
xmlns:tools="url"
the radio button.
study:layout_width="match_pr"
10. drawableBottom, drawableTop, drawableLeft
study:layout_height="match_pr"
And drawableRight : These attribute draw the
study:orientation="vertical"
drawable to the below of the text of RadioButton.
tools:context="url">
For Example : <TextView
study:id="@+id/textView1"
Radio Buttons study:layout_width="fill_pr"
Select your subject? study:layout_height="wrap_cnt"
DBMS study:layout_marginTop="30dp"
C/C++ Programming Radio Buttons in study:gravity="center_horizontal"
Radio Group
Data structures study:textSize="22dp"
Algorithms
study:text="Single Radio Buttons" />
CLEAR SUBMIT <!-- Default RadioButtons -->
<RadioButton
Fig. 4.1.9 Radio button in radio group study:id="@+id/radioButton1"
study:layout_width="fill_pr"
This image shows 4 options of subjects for a question. study:layout_height="wrap_cnt"
In this, each mentioned subject is a Radio Button and study:layout_gravity="center_horizontal"
all the 4 subjects are together enclosed in a Radio study:text="Radio Button 1"
Group. study:layout_marginTop="20dp"
study:textSize="20dp" />
4.1.7 Radio Group <RadioButton
· Radio Group is used to group one or more radio study:id="@+id/radioButton2"
buttons into separate groups based on our study:layout_width="fill_pr"
requirements. study:layout_height="wrap_cnt"
study:text="Radio Button 2"
· In case if we group radio buttons using radio
study:layout_marginTop="10dp"
group, at a time only one item can be selected from
study:textSize="20dp" />
the group of radio buttons
<View
Here's how to use it : study:layout_width="fill_pr"
1. Go to Insert > Form Items > Radio Button Group. study:layout_height="1dp"
This opens the Insert Radio Button Group study:layout_marginTop="20dp"
window. study:background="#B8B894" />
<TextView
2. Enter a name for the group. This will appear in
study:id="@+id/textView2"
your form results. ...
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 16 Designing User Interface with View

study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:layout_marginTop="30dp"
study:gravity="center_horizontal"
study:textSize="22dp"
study:text="Radio button inside RadioGroup" />
<!-- Customized RadioButtons -->
<RadioGroup
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:id="@+id/radioGroup">
<RadioButton
study:id="@+id/radioMale"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:text=" Male"
study:layout_marginTop="10dp"
study:checked="false"
study:textSize="20dp" />
<RadioButton
study:id="@+id/radioFemale"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:text=" Female"
study:layout_marginTop="20dp"
study:checked="false"
study:textSize="20dp" />
</RadioGroup>
<Button
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Show Selected"
study:id="@+id/button"
study:onClick="onclickbuttonMethod"
study:layout_gravity="center_horizontal" />
</LinearLayout>
package radbut;
import study.support.AppCompatActivity;
import study.os.Bundle;
import study.view.View;
import study.widget.Button;
import study.widget.RadioButton;
import study.widget.RadioGroup;
import study.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
RadioButton genderradioButton;
RadioGroup radioGroup;
@Override

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 17 Designing User Interface with View

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View v){
int selectedId =radioGroup.getCheckedRadioButtonId();
genderradioButton = (RadioButton) findViewById(selectedId);
if(selectedId==-1){
Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH_SHORT).show();
}
}
}

Output

4.1.8 Check Box android.view.View

· Check Box belongs to study.widget. Check Box class.

· Android Check Box class is the subclass of


android.widget.TextView
Compound Button class.

· It is generally used in a place where user can select


one or more than choices from a given list of choices. android.widget.Button

· Checkbox is a two states button that can be either


checked or unchecked.
android.widget.
· Checkboxes let you display multiple options to users. CompoundButton
· They can then select whichever options they want.

· Each of the checkboxes can be checked or unchecked


independently of any others. android.widget.CheckBox

Fig. 4.1.10 Check box layout


®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 18 Designing User Interface with View

app:layout_constraintTop_toBottomOf="@+id
Tea Here we have two checkboxes. /checkBox" />
Users can choose tea, coffee
both tea and coffee or neither.
<CheckBox
Coffee study:id="@+id/checkBox3"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
Fig. 4.1.11 Check box
study:layout_marginLeft="144dp"
study:layout_marginTop="28dp"
4.1.8.1 Check Box Attributes study:text="Burger"
1) study:autoText : If set, specifies that this app:layout_constraintStart_toStartOf="parent"
TextView has a textual input method and
automatically corrects some common spelling app:layout_constraintTop_toBottomOf="@+id
errors. /checkBox2" />
<Button
2) study:drawableBottom : This is the drawable to
study:id="@+id/button"
be drawn below the text.
study:layout_width="wrap_cnt"
3) study:drawableRight : This is the drawable to be study:layout_height="wrap_cnt"
drawn to the right of the text. study:layout_marginLeft="144dp"
4) study:editable : If set, specifies that this study:layout_marginTop="184dp"
TextView has an input method. study:text="Order"
app:layout_constraintStart_toStartOf="parent"
5) study:text : This is the Text to display.
Android check box example : app:layout_constraintTop_toBottomOf="@+id
<?xml version="1.0" encoding="utf-8"?> /checkBox3" />
<study.support.constraint.ConstraintLayout </study.support.constraint.ConstraintLayout>
xmlns:study="url"
xmlns:app="ex.//url/apk/res-auto" Let's write the code to check which toggle button is
xmlns:tools="url" ON/OFF.
study:layout_width="match_pr" package example.url.checkbox;
study:layout_height="match_pr" import study.support.AppCompatActivity;
tools:context="url"> import study.os.Bundle;
<CheckBox import study.view.View;
study:id="@+id/checkBox" import study.widget.Button;
study:layout_width="wrap_cnt" import study.widget.CheckBox;
study:layout_height="wrap_cnt" import study.widget.Toast;
study:layout_marginLeft="144dp"
study:layout_marginTop="68dp" public class MainActivity extends AppCompatActivity {
study:text="Pizza" CheckBox pizza,coffe,burger;
app:layout_constraintStart_toStartOf="parent" Button buttonOrder;
app:layout_constraintTop_toTopOf="parent" /> @Override
<CheckBox protected void onCreate(Bundle savedInstanceState) {
study:id="@+id/checkBox2" super.onCreate(savedInstanceState);
study:layout_width="wrap_cnt" setContentView(R.layout.act_main);
study:layout_height="wrap_cnt" addListenerOnButtonClick();
study:layout_marginLeft="144dp" }
study:layout_marginTop="28dp" public void addListenerOnButtonClick(){
study:text="Coffee" //Getting instance of CheckBoxes and Button from the
app:layout_constraintStart_toStartOf="parent" activty_ex.xml file
pizza=(CheckBox)findViewById(R.id.checkBox);
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 19 Designing User Interface with View

coffe=(CheckBox)findViewById(R.id.checkBox2); 4.1.9 Progress Bar


burger=(CheckBox)findViewById(R.id.checkBox3);
· Progress Bar is used to display the progress of an
buttonOrder=(Button)findViewById(R.id.button);
activity while the user is waiting.
· The Progress Bar view provides visual feedback
//Applying the Listener on the Button click
buttonOrder.setOnClickListener about some ongoing tasks, such as when you are
(newView.OnClickListener(){ performing a task in the background.
· For example, you might be downloading some data
@Override from the web and need to update the user about
public void onClick(View view) { the status of the download. In this case, the
int totalamount=0; Progress Bar view is a good choice.
StringBuilder result=new StringBuilder();
· The following activity demonstrates how to use the
result.append("Selected Items:");
Progress Bar view.
if(pizza.isChecked()){
· In android, Progress Bar is a user interface control
result.append("\nPizza 100Rs");
totalamount+=100; which is used to indicate the progress of an
} operation. For example, downloading a file,
if(coffe.isChecked()){ uploading a file.
result.append("\nCoffe 50Rs");
totalamount+=50;
}
ProgressBar
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120; Horizontal ProgressBar
}
result.append("\nTotal: "+totalamount+"Rs"); Fig. 4.1.12 Progress bar
//Displaying the message on the toast
· We can display the android progress bar dialog box
Toast.makeText(getApplicationContext(),
result.toString(), Toast.LENGTH_LONG).show(); to display the status of work being done
} e.g. downloading file, analyzing status of work etc.
}); You can display an indeterminate progress
} (spinning wheel) or result-basedprogress.
}

Output Indeterminate Result-based

Click to Load
Click to Load

Fig. 4.1.13 Intermediate and result-based progress bar


4.1.9.1 Indeterminate
We can display an indeterminate progress bar which
we show to indicate waiting :
<ProgressBar
study:id="@+id/pbLoading"
study:visibility="invisible"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 20 Designing User Interface with View

study:layout_width="wrap_cnt" 4. Widget.ProgressBar.Inverse
study:layout_height="wrap_cnt" />
5. Widget.ProgressBar.Large.Inverse
and then manage the visibility in the activity :
6. Widget.ProgressBar.Small.Inverse
// on some click or some loading we need to wait for...
ProgressBar pb = (ProgressBar) To apply style, you can use below xml settings.
findViewById(R.id.pbLoading); <ProgressBar
pb.setVisibility(ProgressBar.VISIBLE); study:id="@+id/progressBar3"
// run a background job and once complete style="@study:style/Widget.ProgressBar.Large.Inverse"
pb.setVisibility(ProgressBar.INVISIBLE); You can also use android system attr to set progress
Typically you want to try to put the ProgressBar in bar style.
the place where data is going to show (i.e. as a
1. progressBarStyle
placeholder for an image). For a ListView, you put
the ProgressBar in the header or footer, which lets 2. progressBarStyleHorizontal
you put an arbitrary layout outside of the adapter. 3. progressBarStyleLarge
4. progressBarStyleSmall
4.1.9.2 Result-based
ProgressBar can be used to report the progress of a 5. progressBarStyleInverse
long-running AsyncTask. In this case : 6. progressBarStyleLargeInverse
· ProgressBar can report numerical results for a 7. progressBarStyleSmallInverse
task. 8. progressBarStyleSmallTitle
· Must specify horizontal style and result max <ProgressBar
value. study:id="@+id/progressBar2"
style="?study:attr/progressBarStyleHorizontal"
· Must publishProgress(value) in your AsyncTask
3. Common Horizontal Progress Bar Example
<ProgressBar
stydy/result/lout/prog.xml
study:id="@+id/progressBar1"
<!-- Settings for common horizontal progress bar.-->
study:layout_width="wrap_cnt"
<TextView
study:layout_height="wrap_cnt"
study:id="@+id/textView13"
study:visibility="invisible"
study:layout_width="match_pr"
style="?study:attr/progressBarStyleHorizontal"
study:layout_height="wrap_cnt"
study:max="100" />
study:text="Common Horizontal Progress Bar"
1. Android ProgressBar Properties study:textSize="20dp"/>
1. progress : An int value to indicate the progress
bar current progress. <ProgressBar
study:id="@+id/progressBar1"
2. secondaryProgress : An int value to indicate the
style="@study:style/Widget.ProgressBar.Horizontal"
progress bar current secondary progress.
study:max="100"
3. indeterminate : A boolean value. true show a study:layout_width="match_pr"
circle bar. false show a horizontal bar. But study:layout_height="wrap_cnt" />
commonly the bar is decided by it's style value. 4. Customize Horizontal Progress Bar Example
2. Progress Bar Style stydy/result/lout/prog.xml
There are several styles that you can apply to a <!-- Settings for custom horizontal progress bar
progress bar. background, progress and secondProgress.-->
<TextView
1. Widget.ProgressBar.Horizontal study:id="@+id/textView14"
2. Widget.ProgressBar.Large study:layout_width="match_pr"
study:layout_height="wrap_cnt"
3. Widget.ProgressBar.Small
study:text="Custom Horizontal Progress Bar"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 21 Designing User Interface with View

study:textSize="20dp"
study:layout_marginTop="20dp"/>

<ProgressBar
study:id="@+id/progressBar2"
style="?study:attr/progressBarStyleHorizontal" Fig. 4.2.1 List view
study:max="100"
study:minHeight="100dp" · List View uses Adapter classes which add the
study:padding="6dp"
content from data source (such as string array,
study:progressDrawable="@drawable/
array, database etc) to ListView.
/my_progress_bar"
· Adapter bridges data between an Adapter Views
study:layout_width="match_pr"
study:layout_height="wrap_cnt" /> and other Views (List View, Scroll View etc).
· In android Grid View is a view group that display
4.2 List View items in two dimensional scrolling grid (rows and
columns), the grid items are not necessarily
· Android List View is a view which contains the predetermined but they are automatically inserted
group of items and displays in a scrollable list. to the layout using a List Adapter.
· List View is implemented by importing android. · A very common example of ListView is your phone
widget. List View class. contact book, where you have a list of your contacts
· List View uses Adapter classes which add the displayed in a ListView and if you click on it then
content from data source (such as string array, user information is displayed.
array, database etc) to List View.
Adapter :
· Android List View is a view which contains the
group of items and displays in a scrollable list. To fill the data in a ListView we simply use adapters.
List items are automatically inserted to a list using an
· In android, List View is a View Group which is
Adapter that pulls the content from a source such as
used to display the list of scrollable of items in
an arraylist, array or database.
multiple rows and the list items are automatically
inserted to the list using an adapter.
List View in Android Studio
· Generally, the adapter pulls data from a sources
List view is present inside Containers. From there
such as an array or database and converts each item
you can drag and drop on virtual mobile screen to
into a result view and that's placed into the list.
create it. Alternatively you can also XML code to
· The pictorial representation of list view in android create it.
applications is shown in Fig. 4.2.1.

Fig. 4.2.2 List view in Android Studio


®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 22 Designing User Interface with View

Adapter is used to Fill Data in Grid view :


To fill the data in a Grid View we simply use adapter and grid items are automatically inserted to a
Grid View using an Adapter which pulls the content from a source such as an arraylist, array or
database. You can read full Adapter tutorial here.

Grid View in Android Studio


Grid view is present inside Containers. From there you can drag and drop on virtual mobile screen to
create it. Alternatively you can also XML code to create it.

Attributes of List View


Lets see some different attributes of ListView which will be used while designing a custom list :

1. id : id is used to uniquely identify a ListView.


Below is the id attribute's example code with explanation included.
<!-- Id of a list view uniquely identify it-->
<ListView
study:id="@+id/simpleListView"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
/>
2. divider : Thi is a drawable or color to draw between different list items.
Below is the divider example code with explanation included, where we draw red color divider
between different views.
<!--Divider code in ListView-->
<ListView
study:id="@+id/simpleListView"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:divider="#f00"
study:dividerHeight="1dp"
/>
3. dividerHeight : This specify the height of the divider between list items. This could be in
dp(density pixel),sp(scale independent pixel) or px(pixel).
In above example of divider we also set the divider height 1dp between the list items. The height
should be in dp,sp or px.
4. listSelector : listSelector property is used to set the selector of the listView. It is generally orange or
Sky blue color mostly but you can also define your custom color or an image as a list selector as
per your design.
Below is listSelector example code with explanation includes, where list selector color is green,
when you select any list item then that item's background color is green .
<!-- List Selector Code in ListView -->
<ListView
study:id="@+id/simpleListView"
study:layout_width="fill_pr"
study:layout_height="wrap_cnt"
study:divider="#f00"

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 23 Designing User Interface with View

study:dividerHeight="1dp"
study:listSelector="#0f0"/> <!--list selector in green color-->

Example of ListView
<?xml version="1.0" encoding="utf-8"?>
<study.support.constraint.ConstraintLayout xmlns:study="url"
xmlns:app="ex.//url/apk/res-auto"
xmlns:tools="url"
study:layout_width="match_pr"
study:layout_height="match_pr"
tools:context="listview.url.listview.MainActivity">
<ListView
study:id="@+id/listView"
study:layout_width="match_pr"
study:layout_height="fill_pr"
/>
</study.support.constraint.ConstraintLayout>
Create an additional mylist.xml file in layout folder which contains view components displayed in
listview.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:study="url"
study:id="@+id/textView"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Medium Text"
study:textStyle="bold"
study:textAppearance="?study:attr/textAppearanceMedium"
study:layout_marginLeft="10dp"
study:layout_marginTop="5dp"
study:padding="2dp"
study:textColor="#4d4d4d"
/>
Now place the list of data in strings.xml file by creating string-array.
<resources>
<string name="app_name">ListView</string>
<string-array name="array_technology">
<item>C++</item>
<item>Android</item>
<item>Java</item>
<item>Python</item>
</string-array>
</resources>
Activity class

In java class we need to add adapter to listview using setAdapter() method of listview.
package listview.url.listview;
import study.support.AppCompatActivity;
import study.os.Bundle;
import study.view.View;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 24 Designing User Interface with View

import study.widget.AdapterView;
import study.widget.ArrayAdapter;
import study.widget.ListView;
import study.widget.TextView;
import study.widget.Toast;

public class MainActivity extends AppCompatActivity {


ListView listView;
TextView textView;
String[] listItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
listView=(ListView)findViewById(R.id.listView);
textView=(TextView)findViewById(R.id.textView);
listItem = getResources().getStringArray(R.array.array_technology);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listItem);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// TODO Auto-generated method stub
String value=adapter.getItem(position);
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
}
});
}
}

Output

4.2.1 Grid View


· Grid view is a layout in android which lets you arrange components in a two-dimensional scrollable
grid.
· Components in a Gird View are not necessarily static, it can be stored in a List
Adapter(Adapter is like a bridge between data and UI components).
· Following figure shows an example of Grid View in android.
· In android Grid View is a view group that display items in two dimensional
scrolling grid (rows and columns), the grid items are not necessarily
predetermined but they are automatically inserted to the layout using a List
Adapter.
Fig. 4.2.3 Grid view
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 25 Designing User Interface with View

· Users can then select any grid item by clicking on 2) study:columnWidth : This specifies the fixed
it. width for each column. This could be in px, dp,
sp, in, or mm
· Grid View is default scrollable so we don't need to
use Scroll View or anything else with Grid View. 3) study:gravity : Specifies the gravity within each
cell. Possible values are top, bottom, left, right,
· Grid View is widely used in android applications.
center, center_vertical, center_horizontal etc.
· An example of Grid View is very common in
4) study:horizontalSpacing : Defines the default
applications like calculator, calendar ,your default horizontal spacing between columns. This could
Gallery, where you have number of images be in px, dp, sp, in, or mm
displayed using grid, and many others.
5) study:numColumns : Defines how many columns
· In Grid View, grid items are automatically inserted to show. May be an integer value, such as "100"
to the grid view layout using a list adapter. or auto_fit which means display as many
· Generally, the adapter pulls data from a sources columns as possible to fill the available space
such as an array or database and converts each item 6) study:stretchMode : Defines how columns should
into a result view and that's placed into the list. stretch to fill the available empty space, if any.
This must be either of the values :
4.2.1.1 Methods of Grid View a. none : Stretching is disabled
Grid view has many methods to use, some of them
b. spacingWidth : The spacing between each
are explained here
column is stretched
· getAccessibilityClassName(): return the class name
of object. c. columnWidth : Each column is stretched

· getAdapter(): return adapter associated with it.


equally

· getColumnWidth(): return width of a column on d. spacingWidthUniform : The spacing between


grid. each column is uniformly stretched
· getGravity(): return gravity of grid component that 7) study:verticalSpacing : Defines the default
is how they are aligned horizontally. vertical spacing between rows. This could be in
px, dp, sp, in, or mm
· getHorizontalSpacing():
return horizontal spacing
between grid component. Android GridView Example
· getNumColumns(): get number of columns in the Following is the simple example showing user details
grid. using GridView and showing the position of
particular image when clicking on it in android
· setAdapter( ListAdapter adapter): used to set the
applications.
data behind grid view.
· setColumnWidth( int columnWidth): used to set Create a new android application using android
studio and give names as GridView. In case if you
column width.
are not aware of creating an app in android studio
· setGravity( int gravity): used to set gravity of grid's check this article Android Hello World App.
component.
<?xml version="1.0" encoding="utf-8"?>
· setHorizontalSpacing( int horizontalSpacing): used <GridView xmlns:study="url"
to set horizontal spacing to place item in grid. study:id="@+id/gridview"
· setVerticalSpacing( int verticalSpacing): used to set study:layout_width="match_pr"
vertical spacing to place item on grid. study:layout_height="match_pr"
study:columnWidth="110dp"
4.2.1.2 Android Grid View Attributes study:numColumns="auto_fit"
1) study:id : This is the ID which uniquely study:verticalSpacing="10dp"
identifies the layout study:horizontalSpacing="10dp"
study:stretchMode="columnWidth"
study:gravity="center" />
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 26 Designing User Interface with View

Once we are done with creation of layout, we need to create a custom adapter (ImageAdapter.java) by
extending it using BaseExtender to show all the items in the grid.

Open ImageAdapter.java file and write the code like as shown below
package com.study.gridview;
import study.content.Context;
import study.view.View;
import study.view.ViewGroup;
import study.widget.BaseAdapter;
import study.widget.GridView;
import study.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return thumbImages.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageResource(thumbImages[position]);
return imageView;
}
// Add all our images to arraylist
public Integer[] thumbImages = {
S.drwa.Im1, S.drwa.Im2,
S.drwa.Im3, S.drwa.Im4,
S.drwa.Im5, S.drwa.Im6,
S.drwa.Im7, S.drwa.Im8,
};
}

4.2.2 Image View


· At the simplest level, an Image View is simply a view you embed within an XML layout that is used
to display an image (or any drawable) on the screen.
· Image Button has the same property as Image View. Only one feature is extra, which is, images set
through Image Button are clickable, and actions can be attached with them upon clicking.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 27 Designing User Interface with View

Fig. 4.2.4 Image view

· In Android, Image View class is used to display an In Java


image file in application. We can also set the source image at run time
· Image file is easy to use but hard to master in programmatically in java class. For that we use
Android, because of the various screen sizes in setImageResource() method as shown in below
Android devices. example code.
· An android is enriched with some of the best UI /*Add in Oncreate() funtion after setContentView()*/
design widgets that allows us to build good looking ImageView sImVw=(ImageView)
and attractive UI based application. findViewById(R.id.sImVw);
sImVw.setImageResource(R.drawable.lion);//set the source
· See figure below, no matter which folder you put,
in java class
Android will find your image automatically. In this
3. background : Background attribute is used to set
case, both "android.png" and "android3d.png"
the background of a ImageView. We can set a
images are used for demonstration.
color or a drawable in the background of a
Attributes of Image View ImageView.

1. id : id is an attribute used to uniquely identify a Below is the example code in which we set the black
image view in android. Below is the example color in the background and an image in the src
code in which we set the id of a image view. attribute of image view.
<ImageView <ImageView
study:id="@+id/sImVw" study:id="@+id/sImVw"
study:layout_width="fill_pr" study:layout_width="fill_pr"
study:layout_height="wrap_cnt" study:layout_height="wrap_cnt"
/> study:src="@drawable/lion"
2. src : src is an attribute used to set a source file study:background="#000"/><!--black color in
or you can say image in your imageview to background of a image view-->
make your layout attractive.
In Java
Below is the example code in which we set the
We can also set the background at run time
source of a imageview lion which is saved in
programmatically in java class. In below example
drawable folder.
code we set the black color in the background of a
<ImageView
image view.
study:id="@+id/sImVw"
/*Add in Oncreate() funtion after setContentView()*/
study:layout_width="fill_pr"
ImageView sImVw=(ImageView)
study:layout_height="wrap_cnt"
findViewById(R.id.sImVw);
study:src="@drawable/lion" /><!--set the source of an
sImVw.setBackgroundColor(Color.BLACK);//set black color
image view-->
in background of a image view in java class
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 28 Designing User Interface with View

4. padding : padding attribute is used to set the · In android, Scroll View is a kind of layout which is
padding from left, right, top or bottom of the useful to add a vertical or horizontal scroll bars to
Imageview. the content which is larger than actual size of
· paddingRight : Set the padding from the right side layouts such as linear layout, relative layout, frame
of the image view. layout, etc.
· paddingLeft : Set the padding from the left side of · Generally, the android Scroll View is useful when
the image view. we have a content that doesn't fit to our android
· paddingTop : Set the padding from the top side of app layout screen.
the image view. · The Scroll View will enable a scroll to the content
· paddingBottom : Set the padding from the bottom which is exceeding the screen layout and allow
side of the image view. users to see the complete content by scrolling.

· padding : Set the padding from the all side's of the · In android, Scroll View supports only vertical
image view. scrolling.
Below is the example code of padding attribute in 4.2.3.1 Vertically Scrolling
which we set the 30dp padding from all the side's of
To make any content vertically scrollable, simply
a image view.
wrap that content in a ScrollView :
<ImageView
<ScrollView
study:id="@+id/sImVw"
study:layout_width="match_pr"
study:layout_width="fill_pr"
study:layout_height="match_pr">
study:layout_height="wrap_cnt"
<LinearLayout
study:background="#000"
study:layout_width="match_pr"
study:src="@drawable/lion"
study:layout_height="wrap_cnt"
study:padding="30dp"/><!--set 30dp padding from all
study:orientation="vertical" >
the sides-->
<TextView
5. scaleType : scaleType is an attribute used to
study:id="@+id/tv_long"
control how the image should be re-sized or
study:layout_width="wrap_cnt"
moved to match the size of this image view. The
study:layout_height="match_pr"
value for scale type attribute can be fit_xy,
study:text="@string/really_long_string" >
center_crop, fitStart etc. </TextView>
Below is the example code of scale type in which we <Button
set the scale type of image view to fit_xy. study:id="@+id/btn_act"
<ImageView study:layout_width="wrap_cnt"
study:id="@+id/sImVw" study:layout_height="wrap_cnt"
study:layout_width="fill_pr" study:text="View" >
study:layout_height="wrap_cnt" </Button>
study:src="@drawable/lion" </LinearLayout>
study:scaleType="fitXY"/><!--set scale type fit xy--> </ScrollView>

4.2.3 Scroll View 4.2.3.2 Horizontally Scrolling

· Scrolling activity is an important thing to have in In other cases, we want content to horizontally scroll
your app as it gives your user a perfect view when in which case we need to use the Horizontal Scroll
the layout is long. View instead like this :
<HorizontalScrollView
· The Scrolling activity can be implemented easily in
study:layout_width="match_pr"
android studio project because android studio gives
study:layout_height="match_pr">
a ready to use activity.
<LinearLayout
study:layout_width="match_pr"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 29 Designing User Interface with View

study:layout_height="wrap_cnt"
study:orientation="horizontal" > BUTTON ONE BUTTON TWO BUTTON THREE BUTTON
<!-- child views in here -->
</LinearLayout>
</HorizontalScrollView> Fig. 4.2.5 Android horizontal scroll view example

Horizontal Scroll View Example


<?xml version="1.0" encoding="utf-8"?> 4.2.4 Custom Toast Alert
<HorizontalScrollView xmlns:study="url" · In Android, Toast is used to display information for
study:layout_width="match_pr" a period of time.
study:layout_height="wrap_cnt"
· It contains a message to be displayed quickly and
study:fillViewport="true">
disappears after specified period of time.
<LinearLayout xmlns:study="url"
study:orientation="horizontal" · It does not block the user interaction.
study:layout_width="match_pr" · Toast is a subclass of Object class.
study:layout_height="match_pr" · Android Toast can be used to display information
study:layout_marginTop="150dp"> for the short period of time.
<Button study:layout_width="wrap_cnt"
· A toast contains message to be displayed quickly
study:layout_height="wrap_cnt"
and disappears after sometime.
study:text="Button One" />
<Button study:layout_width="wrap_cnt" · A Toast is a message that pops up on the surface of
study:layout_height="wrap_cnt" the window.
study:text="Button Two" /> · It only fills the amount of space required for the
<Button study:layout_width="wrap_cnt" message and the user's current activity remains
study:layout_height="wrap_cnt" visible and interactive.
study:text="Button Three" />
· The notification automatically fades in and out, and
<Button study:layout_width="wrap_cnt"
does not accept interaction events.
study:layout_height="wrap_cnt"
study:text="Button Four" /> · Toast is transient notifications that stay visible for
<Button study:layout_width="wrap_cnt" less than a few seconds before fading out. Toast
study:layout_height="wrap_cnt" don't take focus and its not a modal, so that they
study:text="Button Five" /> don't interrupt the application.
<Button study:layout_width="wrap_cnt" · Toasts are excellent for informing your users of
study:layout_height="wrap_cnt" events without forcing them to open an Activity or
study:text="Button Six" /> browse a Notification.
<Button study:layout_width="wrap_cnt"
· Toast is a mechanism used to display information in
study:layout_height="wrap_cnt"
Android. Unlike Dialog, Toast has no focus, and the
study:text="Button Seven" />
show time is limited.
<Button study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt" · Toast message will disappear automatically after a
study:text="Button Eight" /> certain amount of time. So Toast is generally used
<Button study:layout_width="wrap_cnt" to display prompt messages to users.
study:layout_height="wrap_cnt"
study:text="Button Nine" />
</LinearLayout> Custom Toast In Android
Simple Toast In Android
</HorizontalScrollView>
When we run above example in android emulator we Toast
Custom Toast With Image
will get a result like as shown in Fig. 4.2.5.
Fig 4.2.6 Toast and Custom Toast

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 30 Designing User Interface with View

4.2.4.1 Creating a Toast It created a one Button control in XML Layout file to
Here is an Android Toast example : show the custom toast notification when we click on
Button.
Toast toast = Toast.makeText(getApplicationContext(),
<?xml version="1.0" encoding="utf-8"?>
"This is a message displayed in a Toast",
<LinearLayout xmlns:study="url"
Toast.LENGTH_SHORT); toast.show();
study:id="@+id/custom_toast_layout"
The Toast.makeText() method is a factory method study:orientation="horizontal"
which creates a Toast object. study:layout_width="match_pr"
study.widget.Toast class used to create toast alert study:layout_height="match_pr"
message. study:paddingLeft="10dp"
study:paddingRight="10dp"
Toast alert is a notification message that display for
study:background="#80CC28">
certain amount of time, and automtaically fades out
<ImageView study:src="@drawable/ic_notification"
after set time.
study:layout_width="wrap_cnt"
Use it to show alert message to user.
study:layout_height="wrap_cnt"
Use it for debugging your application. study:layout_marginRight="10dp" />
<TextView study:id="@+id/txtvw"
Use toast alert message to show alert from
study:layout_width="wrap_cnt"
background sevice,boadcast reciever,getting data from
study:layout_height="wrap_cnt"
server...etc.
study:layout_marginTop="13dp"
Normal Toast Alert : study:textColor="#FFF"
//Show alert for short period of time study:textStyle="bold"
Toast.makeText(getApplicationContext(), "This is study:textSize="15dp" />
Toast example.", Toast.LENGTH_SHORT).show(); </LinearLayout>
It loading image (ic_notification) from drawable
//Show alert for long period of time
folder so you need to add your icon in drawable
Toast.makeText(getApplicationContext(), "This is
folder to show it in notification.
Toast example.", Toast.LENGTH_LONG).show();
package com.study.cTEx;
Android Custom Toast Example import study.support.AppCompatActivity;
Create a new android application using android import study.os.Bundle;
studio and give names as ToastExample. In case if import study.view.Gravity;
import study.view.LayoutInflater;
you are not aware of creating an app in android
import study.view.View;
studio check this article Android Hello World App.
import study.view.ViewGroup;
Now open an act_ex.xml file from \res\layout path import study.widget.Button;
and write the code like as shown below. import study.widget.TextView;
<?xml version="1.0" encoding="utf-8"?> import study.widget.Toast;
<LinearLayout xmlns:study="url"
study:layout_width="match_pr" public class MainActivity extends AppCompatActivity {
study:layout_height="match_pr" @Override
study:orientation="vertical" > protected void onCreate(Bundle savedInstanceState) {
<Button super.onCreate(savedInstanceState);
study:id="@+id/btnShow" setContentView(R.layout.act_main);
study:layout_width="wrap_cnt" Button btn = (Button)findViewById(R.id.btnShow);
study:layout_height="wrap_cnt" btn.setOnClickListener(new View.OnClickListener() {
study:text="Show Custom Toast" @Override
study:layout_marginTop="150dp" public void onClick(View v) {
study:layout_marginLeft="110dp"/> LayoutInflater inflater = getLayoutInflater();
</LinearLayout>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 31 Designing User Interface with View

View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup)


findViewById(R.id.custom_toast_layout));
TextView tv = (TextView) layout.findViewById(R.id.txtvw);
tv.setText("Custom Toast Notification");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 100);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
});
}}
It calling our custom toast notification by using LayoutInflater object and showing a toast notification
on Button click.

Output of Android Custom Toast Example

When we run above example using Android Virtual Device (AVD) we will get a result like as shown
below.

4.3 Time and Date Picker

· Android Date Time picker are used a lot in android apps.


· These components are used to select date and time in a customised user interface.
· DatePicker and TimePicker are all extends study.widget.FrameLayout.
· They are used to display date and time selection widget in android application.
· They can be used in either spinner mode or calendar mode (date picker), clock mode (time picker).
You can control their appearance with their properties.

4.3.1 Date Picker Properties


1. datePickerMode : Value can be spinner or calendar. If set to calendar, it will display a calendar
which let you choose date. If set to spinner, it will display a spinner to let you choose date.
2. DatePicker Calendar Mode

< November 2017 < Oct 04 2016


S M T W T F S
1 2 3 4 Nov 05 2017
5 6 7 8 9 10 11
Dec 06 2018
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30

Fig 4.3.1 Date picker spinner mode

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 32 Designing User Interface with View

3. calendarViewShown : This is a boolean value, only take effect when datePickerMode is spinner. If
set to true, it will display a claendar.
4. spinnersShown : This is a boolean value also, only take effect when datePickerMode is spinner.
If set to true, it will display a spinner.
5. If both above two properties set to true of false, it will show both a spinner besides a calendar.
6. minDate : Set the optional minimum date in mm/dd/yyy format.
7. maxDate : Set the maximum date to select, format is mm/dd/yyyy.
8. startYear : Set optional start year.
9. endYear : Set optional end year.

4.3.2 Time Picker Properties


1. timePickerMode : Value can be spinner or clock. When set it' value to clock, it will display a clock.
When set is's value to spinner will display a spinner.

Time Picker Clock Mode


2. headerBackground : This is a Color or

3.35
Drawable resource id which can be set to 2 29
AM
TimePicker's header background. PM 3 30 AM
3. is24HourView() : Check whether it is 24 hour
4 31 PM
time system.
4. setIs24HourView(boolean 24HourView) : Set if Fig. 4.3.2 Time picker spinner mode
use 24 hour time system.
5. getHour() : Get current hour integer value.
6. getMinute() : Get current minute integer value.
7. setOnTimeChangedListener() : Set call back listener when time is changed
Android time picker example

1. TimePicker
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:study="url"
study:layout_width="fill_pr"
study:layout_height="fill_pr"
study:orientation="vertical" >
<Button
study:id="@+id/btnChangeTime"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Change Time" />
<TextView
study:id="@+id/lblTime"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text="Current Time (H:M): "
study:textAppearance="?study:attr/textAppearanceLarge" />
<TextView
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 33 Designing User Interface with View

study:id="@+id/tvTime"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt"
study:text=""
study:textAppearance="?study:attr/textAppearanceLarge" />
<TimePicker
study:id="@+id/timePicker1"
study:layout_width="wrap_cnt"
study:layout_height="wrap_cnt" />
</LinearLayout>
2. Code
Read the code's comment, it should be self-explanatory.
package stud.ex;
import java.util.Calendar;
import and.app.Activity;
import and.app.Dialog;
import and.app.TimePickerDialog;
import study.os.Bundle;
import study.view.View;
import study.view.View.OnClickListener;
import study.widget.Button;
import study.widget.TextView;
import study.widget.TimePicker;

public class MyAct extends Activity {


private TextView tvDisplayTime;
private TimePicker timePicker1;
private Button btnChangeTime;
private int hour;
private int minute;
static final int TIME_DIALOG_ID = 999;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setCurrentTimeOnView();
addListenerOnButton();
}
// display current time
public void setCurrentTimeOnView() {
tvDisplayTime = (TextView) findViewById(R.id.tvTime);
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
tvDisplayTime.setText(
new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 4 - 34 Designing User Interface with View

// set current time into timepicker


timePicker1.setCurrentHour(hour);
timePicker1.setCurrentMinute(minute);
}
public void addListenerOnButton() {
btnChangeTime = (Button) findViewById(R.id.btnChangeTime);
btnChangeTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;

// set current time into textview


tvDisplayTime.setText(new StringBuilder().append(pad(hour))
.append(":").append(pad(minute)));
// set current time into timepicker
timePicker1.setCurrentHour(hour);
timePicker1.setCurrentMinute(minute);
}
};
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}

qqq

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - V

5
5.1 Intent
Activity and
Multimedia with Database
· An intent is to perform an action on the screen. It is
mostly used to start activity, send broadcast
· An Android Intent is an abstract description of an
receiver, start services and send message between
operation to be performed.
two activities.
· It can be used with start Activity to launch an
· There are two intents available in android as
Activity, broadcast Intent to send it to any
Implicit Intents and Explicit Intents. Here is a
interested Broadcast Receiver components, and start
sample example to start new activity with old
Service (Intent) or bind Service (Intent, Service
activity.
Connection, int) to communicate with a background
Service. · Intents are used generally for starting a new activity
using startActivity().
· The intent itself, an Intent object, is a passive data
structure holding an abstract description of an 5.1.1 Use of Intent
operation to be performed.
1. For Launching an Activity
· Android Intent generally consists of two different
portions of information. They have primary and 2. To start a New Service
secondary attributes. Attributes are as follow : 3. For Broadcasting Messages
· A Uniform Resource Identifier (Uri) is nothing but 4. To Display a list of contacts in ListView
an identifier which identifies an abstract or physical
resource. 5.1.2 Types of Intent in Android

· Class is a template. It contains definition of Intent is of two types:


attributes and procedures of similar objects. 1. Implicit Intent 2. Explicit Intent

1. Implicit Intent
INTENT
The implicit intent is the intent where instead of
defining the exact components, you define the action
PRIMARY ATTRIBUTES that you want to perform for different activities.
DATA ACTION
An Implicit intent specifies an action that can invoke
any app on the device to be able to perform an
SECONDARY ATTRIBUTES action. Using an Implicit Intent is useful when your
CATEGORY TYPE app cannot perform the action but other apps
probably can and you'd like the user to pick which
COMPONENT EXTRAS app to use.

Syntax :
Fig 5.1.1 Structure of Intent Intent i=new Intent();
i.setAction(Intent.ACTION_SEND);

(5 - 1)® - An up thrust for knowledge


TECHNICAL PUBLICATIONS
Mobile Application Development 5-2 Activity and Multimedia with Databases

· There are some other standard actions that intents can use to launch a specific app component, such as
can use for launching activities. a particular activity or service in your app.

Example of Implicit Intent Syntax :


If you want the Android System to choose from the Intent I = new Intent(getApplicationContext(),
applications present in the mobile device to perform NextActivity.class);
a particular task then we use Implicit Intent. For I.putExtra("value1" , "This value for Next Activity");
example, if you want to send images then the I.putExtra("value2" , "This value for Next Activity");
Android System will provide options of Gmail, Example of Explicit Intent
Instagram, Fb, WhatsApp, etc. Here, you have to pass
By using Explicit Intent you can launch a component
the action type and with the help of this action type,
by providing the fully-qualified address of the
the system will call the desired application.
component i.e. you want to launch a particular
// Create the text message with a string
component only. To use Explicit Intent, you have to
val sendIntent = Intent().apply {
make an Intent object.
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, textMessage) // Executed in an Activity, so 'this' is the Context
type = "text/plain" // The fileUrl is a string URL, such as "url"
} val downloadIntent = Intent(this,
// Verify that the intent will resolve to an activity DownloadService::class.java)
if (sendIntent.resolveActivity(packageManager) != null) { dwdIntent.data = Uri.parse(fileUrl)
startActivity(sendIntent) startService(downloadIntent)
} Here, in the above example, we can see that the
In the above example, when the startActivity() is Intent constructor is used to create an Intent and in
called then the system will scan for the applications the constructor, we have passed the current context
that can send the text messages and will provide the and the desired component to be launched. Here, the
user a list of applications that can do the same. DownloadService is explicitly called.

5.1.3 Intent Filter


2. Explicit Intent
· An intent filter is an expression in an app's manifest
An explicit intent is an Intent where you explicitly
file that specifies the type of intents that the
define the component that needs to be called by the
component would like to receive.
Android System. An explicit intent is one that you

1 Device
Intent fired to
launch activity B

Activity 1 ANDROID
SYSTEM Activity B
Intent 2

Manifest : Comparing
intent filter contents of Launching activity B
intent and
intent filter at
3

Fig 5.1.2 Internal structure of intent filter

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-3 Activity and Multimedia with Databases

· For instance, by declaring an intent filter for an Constructing Android Intent


activity, you make it possible for other apps to As we know that android system identifies the
directly start your activity with a certain kind of component from intent. Thus intent object contains
intent. information such as name of the component or the
· An Android intent filter is an expression. It is category of the component. It also contains
expressed in the Android application's manifest file. information for the recipient. It determines which
· It defines the type of intent the component need to
action it has to perform when the intent is received.
receive.
Name of the component :
· For an implicit intent, intent filter is required. If · It is optional. It contains the exact name of the
there is no intent filter for an activity, then only an component which it has to initiate. It is a very
explicit intent can initiate it. strong requirement for the explicit intent as only
· For security purpose, the intent filter should not be that component will be initiated whose name is
used for service. Service may start without notifying explicitly mentioned.
the user and runs in the background. · For example, you want to send a courier then you
have to mention the name of your best friend as
5.1.3.1 Work of Intent
writing only "To my best friend is not going to
With an explicit intent, the app is started directly.
work". So here, Courier is the thing that you want
With implicit intents, intent filter is used to filter out
your best friend (component) to read or do some
the component to start. Intents are used to perform
action. Courier service is your explicit intent.
three things mainly and they are as follows :
· Component name should be specified with a fully
1. Activity is started : There is a method called start qualified name. The package name is to be
Activity() . When we pass intent to this method a mentioned. In the Fig. 5.1.2, package name is
new instance of that activity is started. Intent indicated as Manifest : Intent Filter.
contains important information about the data
· If name is not mentioned then intent becomes
and gives details about that activity which is to
implicit.
be started. Not only this, we can have result
from other activity with the help of intent and Action of Intent :
methods like start Activity For Result() and on · It is a set of characters which specifies the general
Activity Result() respectively. But that part we action of intent. Actions can be specified, i.e., you
are going to discuss in the next section which is can create your own intent action.
dedicated for activities.. · Lot of keywords isn't it. Let's resolve them one by
2. Service Activation : Similarly, there is a method one.
called start Service(). When we pass intent to · Keywords static is used for those variables which
this method service is started. This intent gives are common to all objects in a single class in case of
details about the service which is to be started. If JAVA language. These variables are alive in the
we want to get a result or want to have a complete run of the program.
server-client set up, then we can do it with a · Then public keyword is used to grant access. It
method called bind Service(). This will be allows access to all other methods and they can be
discussed in the section dedicated for services. modified by other classes.
3. Sending Broadcast : There are three methods · Keyword final is used so that no method can
named send Broadcast(), send Ordered Broadast() modify it even if it has access to that variable. In
and send Sticky Broadcast(). Any broadcast can the above statement, DOCOUNT is the name of the
be delivered to apps by passing intent to one of action.
these methods.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-4 Activity and Multimedia with Databases

Data : 5.2 Activity Life Cycle


· A URI object is required. It is used to reference the
· An activity is the single screen in android. It is like
data which is to be acted upon. It may reference the
MIME type of data. Intent's action dictates the type window or frame of Java.
of available data. If action is ACTION_SEND then · By the help of activity, you can place all your UI
the user must have some data to share. components or widgets in a single screen.
· The Internet media type is an identifier which · Android Activity Lifecycle is controlled by 7
indicates the type of data in file on the internet. methods of android.app.Activity class.
They are also called Content-types. · The android Activity is the subclass of
· Internet media types are also used as a set of rules ContextThemeWrapper class.
to provide communication between different · An activity is the single screen in android. It is like
applications. Say, type audio has MIME type : window or frame of Java.
audio/mp4 for MP4 audio, audio/mpeg for MP3 or · In android, Activity represents a single screen with
other MPEG audio, etc. a user interface (UI) of an application and it will
· Now for intents, it is very important to keep clear acts an entry point for users to interact with an app.
of all the issues between Uri format and MIME See Fig 5.2.1 on next page
type, especially in the case of methods.
· setData() method is used to set data for Uri and Android Activity Lifecycle Callback Methods
setType() to set type of MIME. Now both of them · In android, an activity goes through a series of
are like positive and negative forces which cancel states during its lifetime. By using callback methods
out each other. we can get the activity transitions between the
states.
Category :
· Android system initiates its program within an
· Most intents don't require a category. Additional
Activity starting with a call on onCreate() callback
information is given about the component.
method. There is a sequence of callback methods
· This component, which is going to handle the that start up an activity and a sequence of callback
intent. methods that tear down an activity.
· There can be multiple categories for single intent. · This section will give you a detailed information
We have already discussed about them. about callback methods to handle activity transitions
Extras : between states during lifecycle.
· These are the key-value pairs. They contain extra 1. onCreate() :
information for the fulfillment of the action
It is the first method to be called when any activity is
requested in intent. putExtra() method is used to
first created. All the invariant set up are to be
add extra data.
initiated in this method. Views are created, bind data,
· A Bundle object can be created with additional data
etc. A Bundle object is passed where all the previous
and introduced to intent with putExtras() method.
activity states are captured.
Flags : It is followed by onStart() method.
· They act as data about data, i.e., a metadata for
intent. At this state, activity cannot be killed by the system.

· It may instruct the system about the nature of This is the first callback method and it fires when the
treatment to be given to an activity which is system creates an activity for the first time. During
launched by this intent. the activity creation, activity entered into a Created
state.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-5 Activity and Multimedia with Databases

Activity
launched

onCreate()

onStart() onRestart()

onResume()
User navigates
to the activity
Activity
App process running
killed

Another activity comes


into the foreground
User returns
to the activity
User with higher priority
onPause()
need memory
The activity is
no longer visible User navigates
to the activity

onStop()

The activity is finishing or


being destroyed by the system

onDestroy()

Activity
shut down

Fig 5.2.1 Activity Life Cycle

If we have an application start-up logic that needs to


Once onCreate() method execution is finished, the
perform only once during the life cycle of an activity,
activity will enter into Started state and system calls
then we can write that logic in onCreate() method.
the onStart() method.
Following is the example of defining a onCreate()
method in android activity. 2. onRestart() :
@Override If the activity is paused and that activity is to be
protected void onCreate(Bundle savedInstanceState) { restarted then this method is called.
super.onCreate(savedInstanceState);
It is always followed by onStart().
setContentView(R.layout.act_main);
} The system cannot kill this activity at this state.

The system will invoke onRestart() method when an


activity restarting itself after stopping it.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-6 Activity and Multimedia with Databases

The onRestart() method will restore the state of The app will stays in this Resumed state until an
activity from the time that is being stopped. another activity happens to take focus away from the
app like getting a phone call or screen turned off, etc.
The onRestart() callback method in android activity
will always followed by onStart() method. In case if any interruption events happen in Resumed
state, the activity will entered into Paused state and
3. onStart() : the system will invoke onPause() method.
App becomes visible after this method is called. After an activity returned from Paused state to
It is followed by onResume when activity is in the Resumed state, the system again will call onResume()
foreground method due this we need to implement onResume()
method to initialize the components that we release
It is followed by onStop() when activity is hidden.
during onPause() method
At this state, system cannot kill the activity.
Following is the example of defining a onResume()
The onStart() callback method will invoke when an method in android activity.
activity entered into Started State by completing @Override
onCreate() method. The onStart() method will make public void onResume() {
an activity visible to the user and this method super.onResume();
execution will finish very quickly. if (mCamera == null) {
initializeCamera();
Following is the example of defining a onStart()
}
method in android activity.
}
@Override If any interruption happen in Resumed state, the
protected void onStart()
activity will entered into Paused state and the system
{
will invoke onPause() method.
super.onStart()
}
5. onPause() :
After completion of onStart() method execution, the
If activity wants to resume then this method is called.
activity enters into Resumed state and system invoke
This saves all the unsaved changes. Anything which
the onResume() method.
is consuming CPU is stopped. The next stage is not
4. onResume() : started until control returns from paused state. Hence
this stage has a very short life span.
When activity starts interacting onResume() is called.
User interacts with activity and gives the input. It is If activity has to come to foreground then it is to be
at the top of back stack now. followed by onResume().

It is always followed by onPause(). If it becomes invisible then onStop() method is called


after this.
System cannot kill activity at this stage also.
System can kill at this stage.
When an activity entered into Resumed state, the
system invoke onResume() call back method. In this Whenever the user leaves an activity or the current
state activity start interacting with user that means activity is being Paused then the system invoke
user can see the functionality and designing part of onPause() method. The onPause() method is used to
an application on the single screen. pause an operations like stop playing the music when
the activity is in paused state or pass an activity
Mostly the core functionality of an app is
while switching from one app to another app because
implemented in onResume() method.
every time only one app can be focused.

Following is the example of defining a onPause()


method in android activity.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-7 Activity and Multimedia with Databases

@Override 7. onDestroy() :
public void onPause() { When activity has to be destroyed, then this method
super.onPause(); is called. It is the final call. It is either called when
if (mCamera != null) { activity is about to finish or it is going to be replaced
mCamera.release(); to save space.
mCamera = null;
} It is not followed by any call as it is final.
} The system kills this activity.
After completion of onPause() method execution, the
next method is either onStop() or onResume() The system will invoke onDestroy() method before an
depending on what happens after an activity entered activity is destroyed and this is the final callback
into Paused state. method which received by the android activity.

The system will invoke this onDestory() callback


6. onStop() : method either the activity is finishing or system
In this case either activity is destroyed or it is destroying the activity to save space.
overtaken by any other activity. It is called when
Following is the example of defining a onDestroy()
activity becomes invisible.
method in android activity.
If activity wants user re-interaction then this is @Override
followed by onRestart() method. public void onDestroy()
{
If this activity has to go away then it is followed by
super.onDestroy();
onDestroy() method.
}
System can kill the activity at this stage. The onDestroy() method will release all the resources
which are not released by previous callback onStop()
The system will invoke onStop() callback method
method.
when an activity no longer visible to the user, the
activity will enter into Stopped state. This happens 5.2.1 Understanding the Activity Lifecycle
due to current activity entered into Resumed state or
· The activity lifecyle has four states.
newly launched activity covers complete screen or it's
been destroyed. 1. When the activity is on the foreground of the
application, it is the running activity. Only one
The onStop() method is useful to release all the app activity can be in the running state at a given
resources which are no longer needed to the user. time.
Following is the example of defining a onStop() 2. If the activity loses focus but remains visible
method in android activity. (because a smaller activity appears on top), the
@Override activity is paused.
protected void onStop()
3. If the activity is completely covered by another
{
running activity, the original activity is stopped.
super.onStop();
When an activity stops, you will lose any state
}
and will need to re-create the current state of
the user interface when the activity is restarted.
The next callback method which raised by system is
either onRestart(), in case if the activity coming back 4. While the activity is paused or stopped, the
to interact with the user or onDestroy(), in case if the system can kill it if it needs to reclaim memory.
activity finished running. The user can restart the activity.
· As you have seen, an activity is simply a screen or
user interface in an Android application-either a full

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-8 Activity and Multimedia with Databases

screen or a floating window that a user interacts 5.2.2.1 Types of Broadcasts


with. There are two types of broadcasts received by
· An Android app is made up of different activities receivers and they are :
that interact with the user as well as one another.
For example, a simple calculator would use one Broadcasts
single activity.
· If you enhanced the calculator app to switch
between a simple version and a scientific version,
Normal Ordered
you would then use two activities. broadcasts broadcasts
· Every Android application runs inside its own
process. Processes are started and stopped to run an Fig 5.2.2 Types of Broadcasts
application and also can be killed to conserve
1. Normal Broadcasts
memory and resources.
· These are asynchronous broadcasts.
· Activities, in turn, are run inside the main UI
· Receivers of this type of broadcasts may run in
thread of the application's process.
any order, sometimes altogether.
· Once an activity is launched, it goes through a
lifecycle, a term that refers to the steps the activity · This is efficient.
progresses through as the user (and OS) interacts · Receivers cannot use the result.
with it. · They cannot abort the included APIs.
· There are specific method callbacks that let you
· These broadcasts are sent with
react to the changes during the activity lifecycle.
Context.sendBroadcast
5.2.2 Broadcast Life Cycle 2. Ordered Broadcasts
· Broadcast receiver is an Android component which · These are synchronous broadcasts.
allows you to send or receive Android system or
· One broadcast is delivered to one receiver at a
application events.
time.
· Broadcast Receivers simply respond to broadcast
· Receivers can use the result. In fact as each
messages from other applications or from the
system itself. These messages are sometime called receiver executes, result is passed to next receiver.
events or intents. · Receiver can abort the broadcast and hence no
· For example, applications can also initiate broadcast is received by other receivers.
broadcasts to let other applications know that some · The order of receivers is managed and controlled
data has been downloaded to the device and is by the attribute study:priority in corresponding
available for them to use, so this is broadcast intent-filter.
receiver who will intercept this communication and
· If receivers will have same priority then they may
will initiate appropriate action.
run in any order.
· Android Broadcast Receiver is one of the principal
components of Android application development. · There are following two important steps to make

· Broadcast receiver which is also known as receiver


Broadcast Receiver works for the system
is a component of android application broadcasted intents ?
· Creating the Broadcast Receiver
· Registering Broadcast Receiver
There is one additional steps in case you are going to
implement your custom intents then you will have to
create and broadcast those intents.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5-9 Activity and Multimedia with Databases

What is Android Broadcast Receiver ?


A broadcast receiver is a dormant component of
Registers for Intents to observe
the Android system. Only an Intent (for which it
is registered) can bring it into action. The
Broadcast Receiver's job is to pass a notification to
the user, in case a specific event occurs. Android Broadcast
system receiver
Using a Broadcast Receiver, applications can
register for a particular event. Once the event
occurs, the system will notify all the registered Gets notification when Intents occur
applications.
Fig 5.2.3 Android Broadcast Receiver
There are two types of broadcasts received by
receivers and they are :
· Normal Broadcasts :
These are asynchronous broadcasts. Receivers of this type of broadcasts may run in any order,
sometimes altogether. ...
· Ordered Broadcasts :
These are synchronous broadcasts. One broadcast is delivered to one receiver at a time.
· System Broadcasts
There are many system level services which broadcast messages at system wide level which can be
used. These are intents which signal changes. Some of the native actions are listed in the following
table :

Sr. No. Action Name Description

1 ACTION_BOOT_COMPLETED When device completes its start up sequence then this broadcast is
fired. This broadcast is received only when the application has the
RECEIVE_BOOT_COMPLETED permission.

2 ACTION_CAMERA_BUTTON This broadcast is fired when camera is clicked

3 ACTION_DATE_CHANGED, When date and/ or time are changed manually then these
ACTION_TIME_CHANGED broadcasts are fired respectively.

4 ACTION_MEDIA_EJECT Before external storage media is ejected, this broadcast is fired. To


save and close any opened files which were read from or written
to external storage media, application should listen to this
broadcast.

5 ACTION_MEDIA_MOUNTED, When any external storage media is added and / or removed, these
ACTION_MEDIA_UNMOUNTED broadcasts are fired.

6 ACTION_NEW_OUTGOING_CALL When a new outgoing call is placed this broadcast is fired

7 ACTION_SCREEN_ON, When screen turns on and/or turns off, this broadcast is fired.
ACTION_SCREEN_OFF

8 ACTION_TIMEZONE_CHANGED Whenever device’s current time zone is changed this broadcast is


fired.

Table 5.2.1 Native Broadcasts

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 10 Activity and Multimedia with Databases

Common Methods
Let us study some of the common methods and they are as follows :

1.abortBroadcast() :
· This method doesn't works with asynchronous broadcasts.
· It sets the flag which indicates that the present receiver should abort this broadcast.
· Other broadcast receivers will be prevented from receiving this broadcast.
· Syntax: public final void abortBroadcast();

2.clearAbortBroadcast() :
· The flag set by abortBroadcast() method is cleared by this function call.
· Syntax: public final void clearAbortBroadcast();

3.getAbortBroadcast() :
· This method returns the flag which signals broadcast receiver to abort the current broadcast or not.
· Syntax: public final Boolean getAbortBroadcast();

4. getDebugUnregister() :
· This returns the previous value given to setDebugUnregister(boolean)
· Syntax: public final Boolean getDebugUnregister();

5.getResultCode() :
· Previous receiver sets a result code.
· This current result code is retrieved by this method.
· Result data is integer
· Syntax: public final intgetResultCode();

6.getResultData() :
· Previous receiver sets a result data.
· It may be null.
· Current result data I retrieved by this method.
· Result data is of type string
· Syntax: public final String getResultData();

7.isInitialStickyBroadcast() :
· If receiver is processing the initial value of a sticky broadcast then this method returns true.
· This has nothing to do with current broadcast.
· It is the value of last broadcast and is held in sticky cache.
· Syntax: public final Boolean isInitialStickyBroadcast();

8.isOrderedBroadcast() :
· When receiver processes a broadcast from ordered broadcast, this method returns true.
· Syntax: public final Boolean isOrderedBroadcast();
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 11 Activity and Multimedia with Databases

9.onReceive(Context,Intent) :
· When broadcast receiver receives some kind of broadcast intent then this method is called.
· Current results can be viewed or modified using other methods when this method was in use.
· By default, this method is associated with the main thread of application.
· If <receiver/> tag is used then as soon as function returns the object is killed.
· Context is in which the receiver is running
· Intent which is intended to be received.
· Syntax: public abstract void onReceive(Context context, Intent intent);

10.setOrderedHint(boolean) :
· This hints whether broadcast receiver is running on ordered mode or not.
· Syntax: public final void setOrederedHint(Boolean isOrdered);

Android Broadcast Example


This application will demonstrate the broadcast receiver's function.
?
<RelativeLayout xmlns:android="url"
xmlns:tools="url"
study:layout_width="match_parent"
study:layout_height="match_parent"
study:paddingBottom="@dimen/act_vertical_margin"
study:paddingLeft="@dimen/act_horizontal_margin"
study:paddingRight="@dimen/act_horizontal_margin"
study:paddingTop="@dimen/act_vertical_margin"
tools:context=".MainActivity" >
<EditText
study:id="@+id/broadcastedit"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:layout_alignParentTop="true"
study:layout_marginTop="81dp"
study:ems="10"
study:text="Broadcast message" >
<requestFocus />
</EditText>
<Button
study:id="@+id/sendBroad"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:layout_alignLeft="@+id/broadcastedit"
study:layout_below="@+id/broadcastedit"
study:layout_marginTop="16dp"
study:onClick="broadcastCustomIntent"
study:text="Broadcast" />
</RelativeLayout>
Mobile Application Development 5 - 12 Activity and Multimedia with Databases

Now the corresponding graphical layout should be similar to the following snapshot:

Fig. 5.2.4 Graphical layout of BroadcastReceiverEx App

It's the time for our MainActivity.java file. Open it and type the code as shown below :
package ex.Broadcast;
import android.app.Activity;
import study.content.Intent;
import study.os.Bundle;
import study.view.View;
import study.view.View.OnClickListener;
import study.widget.Button;
import study.widget.EditText;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
// Button broadcast = (Button) findViewById(R.id.sendBroad);
}
public void broadcastCustomIntent(View v) {
Intent intent = new Intent("MyCustomIntent");
EditText edit = (EditText) findViewById(R.id.broadcastedit);
intent.putExtra("broadcast", (CharSequence) edit.getText().toString());
intent.setAction("ex.Broadcast.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
For a broadcast receiver there has to be a receiver to receive the broadcast. In this case, we have to
create a new class. Create a new class by right clicking over the package name and add a class. Name
it as you like.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 13 Activity and Multimedia with Databases

package ex.Broadcast;
import study.content.BroadcastReceiver;
import study.content.Context;
import study.content.Intent;
import study.widget.Toast;
public class BroadcastClass extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
CharSequence inData = arg1.getCharSequenceExtra("broadcast");
Toast.makeText(arg0, "Hello Readers!! Enjoying broadcasts :)" + inData,
Toast.LENGTH_SHORT).show();
}
}
Code for Android Receiver

The last work you have to do is open your manifest file and add the code as shown below :
?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="url"
package="ex.Broadcast"
study:versionCode="1"
study:versionName="1.0" >
<uses-sdk
study:minSdkVersion="8"
study:targetSdkVersion="18" />
<uses-permission study:name="android.permission.READ_PHONE_STATE" />
<application
study:allowBackup="true"
study:icon="@drawable/ic_launcher"
study:label="@string/app_name"
study:theme="@style/AppTheme" >
<activity
study:name="ex.Broadcast.MainActivity"
study:label="@string/app_name" >
<intent-filter>
<action study:name="android.intent.action.MAIN" />
<category study:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver study:name="BroadcastClass" >
<intent-filter>
<action study:name="ex.Broadcast.CUSTOM_INTENT" />
</intent-filter>
</receiver>
</application>

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 14 Activity and Multimedia with Databases

Save everything and run your emulator. Now run your application. The output should be similar to
the snapshot listed below :

Fig. 5.2.5 Initial Output of Android App on Emulator

Now enter the message you want to broadcast and press the button and see the magic what you
wanted to broadcast is actually broadcasted.

Fig. 5.2.6 Message is broadcasted


5.3 Content Provider

· A Content Provider manages access to a structured set of data.


· It encapsulates the data and provides mechanisms for defining data security.
· Content Provider is the standard interface that connects data in one process with code running in
another process.
· A content provider component supplies data from one application to others on request.
· Content Providers support the four basic operations, normally called CRUD - operations. CRUD is the
acronym for create, read, update and delete.
· A content provider manages access to a central repository of data.
· Typically you work with content providers in one of two scenarios; you may want to implement
code to access an existing content provider in another application, or you may want to create a new
content provider in your application to share data with other applications.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 15 Activity and Multimedia with Databases

AbstractThreadedSyncAdapter CursorLoader

Widgets

Other applications ContentProvider

Search

Data storage Data storage

Fig. 5.3.1 Forms of content provider

· Content providers can help an application manage access to data stored by itself, stored by other
apps, and provide a way to share data with other apps.
· They encapsulate the data, and provide mechanisms for defining data security.
· Content providers are the standard interface that connects data in one process with code running in
another process.
· Implementing a content provider has many advantages. Most importantly you can configure a content
provider to allow other applications to securely access and modify your app data as illustrated in
Fig. 5.3.2.

Your application

Your content
provider Other applications
implementation

Your data
storage

Fig. 5.3.2 Overview diagram of how content providers manage access to storage

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 16 Activity and Multimedia with Databases

5.3.1 Creating a Content Provider 3) update() - This method will update an existing
To create a content provider in android applications rows in our content provider and it return the
we should follow below steps. number of rows updated.

· We need to create a content provider class that 4) delete() - This method will delete the rows in our
content provider and it return the number of
extends the Content Provider base class.
rows deleted.
· We need to define our content provider URI to
5) getType() - This method will return the MIME
access the content.
type of data to given content URI.
· The Content Provider class defines a six abstract 6) onCreate() - This method will initialize our
methods (insert(), update(), delete(), query(), provider. The android system will call this
getType()) which we need to implement all these method immediately after it creates our provider.
methods as a part of our subclass. Android Content Provider Example
· We need to register our content provider in · Following is the example of using Content Provider
AndroidManifest.xml using <provider> tag. in android applications. Here we will create our
Following are the list of methods which need to own content provider to insert and access data in
implement as a part of Content Provider class. android application.
· Create a new android application using android
studio and give names as ContentProvider. In case
if you are not aware of creating an app in android
Content provider
studio check this article Android Hello World App.
· Now we need to create our own content provider
query()
file UsPr.java in
\src\main\study\ex.contentprovider path to define
insert()
our actual provider and associated methods for that
update() right click on your application folder ? Go to New ?
select Java Class and give name as UsPr.java.
delete() · Once we create a new file UsPr.java, open it and
write the code like as shown below
getType()

onCreate() package ex.contentprovider;


import study.content.ContentProvider;
import study.content.ContentUris;
import study.content.ContentValues;
import study.content.Context;
Fig 5.3.3 Content provider methods
import study.content.UriMatcher;
1) query() - It receives a request from the client. By import study.db.Cursor;
using arguments it will get a data from requested import study.db.sqlite.SQLiteDatabase;
table and return the data as a Cursor object. import study.db.sqlite.SQLiteException;
2) insert() - This method will insert a new row into import study.db.sqlite.SQLiteOpenHelper;
our content provider and it will return the import study.db.sqlite.SQLiteQueryBuilder;
import study.net.Uri;
content URI for newly inserted row.
import java.util.HashMap;

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 17 Activity and Multimedia with Databases

public class UsersProvider extends ContentProvider {


static final String PROVIDER_NAME = "ex.contentprovider.UsPr";
static final String URL = "content://" + PROVIDER_NAME + "/users";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String id = "id";
static final String name = "name";
static final int uriCode = 1;
static final UriMatcher uriMatcher;
private static HashMap<String, String> values;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);
uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case uriCode:
return "vnd.android.cursor.dir/users";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);

switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = id;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 18 Activity and Multimedia with Databases

}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.update(TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.delete(TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
private SQLiteDatabase db;
static final String DATABASE_NAME = "EmpDB";
static final String TABLE_NAME = "Employees";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 19 Activity and Multimedia with Databases

+ " name TEXT NOT NULL);";

private static class DatabaseHelper extends SQLiteOpenHelper {


DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}

XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="url"
study:orientation="vertical" study:layout_width="match_parent"
study:layout_height="match_parent">
<TextView
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:text="Name"
study:layout_marginLeft="100dp"
study:layout_marginTop="100dp"/>
<EditText
study:id="@+id/txtName"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:layout_marginLeft="100dp"
study:ems="10"/>
<Button
study:id="@+id/btnAdd"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:onClick="onClickAddDetails"
study:layout_marginLeft="100dp"
study:text="Add User"/>
<Button
study:id="@+id/btnRetrieve"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:onClick="onClickShowDetails"
study:layout_marginLeft="100dp"
study:text="Show Users"/>

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 20 Activity and Multimedia with Databases

<TextView
study:id="@+id/res"
study:layout_width="match_parent"
study:layout_height="wrap_content"
study:layout_marginLeft="100dp"
study:clickable="false"
study:ems="10"/>
</LinearLayout>

package ex.contentprovider;
import study.content.ContentValues;
import study.content.Context;
import study.db.Cursor;
import study.net.Uri;
import study.ex;
import study.os.Bundle;
import study.view.MotionEvent;
import study.view.View;
import study.view.inputmethod.InputMethodManager;
import study.widget.EditText;
import study.widget.TextView;
import study.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
public void onClickAddDetails(View view) {
ContentValues values = new ContentValues();
values.put(UsersProvider.name, ((EditText) findViewById(R.id.txtName)).getText().toString());
getContentResolver().insert(UsersProvider.CONTENT_URI, values);
Toast.makeText(getBaseContext(), "New Record Inserted", Toast.LENGTH_LONG).show();
}
public void onClickShowDetails(View view) {
// Retrieve employee records
TextView resultView= (TextView) findViewById(R.id.res);
Cursor cursor = getContentResolver().query(Uri.parse("content://ex.contentprovider.UsPr/users"), null, null, null, null);
if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 21 Activity and Multimedia with Databases

strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}
}

(ActivityManifest.xml) using <provider> attribute like as shown below.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="url" package="ex.contentprovider">
<application
study:allowBackup="true"
study:icon="@mipmap/ic_launcher"
study:label="@string/app_name"
study:roundIcon="@mipmap/ic_launcher_round"
study:supportsRtl="true"
study:theme="@style/AppTheme">
<activity study:name=".MainActivity">
<intent-filter>
<action study:name="android.intent.action.MAIN" />
<category study:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
study:authorities="ex.contentprovider.UsPr"
study:name=".UsersProvider">
</provider>
</application>
</manifest>
Output of Android Content Provider Example
When we run above example in android emulator we will get a result like as shown below

Fig. 5.3.4

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 22 Activity and Multimedia with Databases

Why does Android System need Content A fragment can implement a behaviour that has
n
Providers ?
no user interface component.
· The need for Content Providers arises because the
· To create a fragment, you must create a subclass of
database created in one application is not visible to
Fragment (or an existing subclass of it).
a second application.
· The Fragment class has code that looks a lot like an
· It is simple to create and store database in different
Activity.
applications using SQLite, however the problem is
this, a database in Android is private to the Fragment is
application that creates it. There is no common added
storage area in Android that every application can
access. Therefore, for different applications to use a onAttach()
database, Android system needs an interface that
allows such inter-application and inter-process data
onCreate()
exchange. This is where content provider comes to
play.
onCreateView()
5.3.2 Fragments
· In Android, Fragment is a part of an activity which
onActivityCreated()
enable more modular activity design. It will not be
wrong if we say a fragment is a kind of
onStart()
sub-activity.
· It represents a behaviour or a portion of user
interface in an Activity. onResume()

· Using Fragments also allows you to separate


components into their own classes (Fragments), Fragment is
rather than having too much logic in a single added

Activity User navigates The fragment is


backward or added to the back
· A Fragment is a piece of an activity which enable fragment is stack, then
more modular activity design. It will not be wrong removed/replaced removed/replaced
if we say, a fragment is a kind of sub-activity.
onPause()
5.3.2.1 Creating a Fragment
· Following are important points about fragment ? onStop()
(Refer Fig. 5.3.5) The fragment
returners to the
n A fragment has its own layout and its own onDestroyView() layout from the
behaviour with its own life cycle callbacks. back stack

n You can add or remove fragments in an activity


while the activity is running. onDestroy()

n You can combine multiple fragments in a single


activity to build a multi-pane UI. onDetach()

n A fragment can be used in multiple activities.


n Fragment life cycle is closely related to the life Fragment is
destroyed
cycle of its host activity which means when the
activity is paused, all the fragments available in Fig. 5.3.5 The lifecycle of a fragment (while its activity
the activity will also be stopped. is running)

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 23 Activity and Multimedia with Databases

· It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and
onStop().
· In fact, if you're converting an existing Android application to use fragments, you might simply move
code from your activity's callback methods into the respective callback methods of your fragment.
· Usually, you should implement at least the following lifecycle methods :
1. onCreate()

The system calls this when creating the fragment. Within your implementation, you should initialize
essential components of the fragment that you want to retain when the fragment is paused or stopped,
then resumed.

2. onCreateView()

The system calls this when it's time for the fragment to draw its user interface for the first time. To
draw a UI for your fragment, you must return a View from this method that is the root of your
fragment's layout. You can return null if the fragment does not provide a UI.

3. onPause()

The system calls this method as the first indication that the user is leaving the fragment (though it
doesn't always mean the fragment is being destroyed). This is usually where you should commit any
changes that should be persisted beyond the current user session (because the user might not come
back).

5.3.2.2 Types of Fragments


Basically fragments are divided as three stages as shown below.
· Single frame fragments - Single frame fragments are using for hand hold devices like mobiles, here
we can show only one fragment as a view.
· List fragments - Fragments having special list view is called as list fragment
· Fragments transaction - Using with fragment transaction. we can move one fragment to another
fragment.
Android Fragment Example

Let's have a look at the simple example of android fragment.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="url"
xmlns:app="ex/apk/res-auto"
xmlns:tools="url"
study:layout_width="fill_parent"
study:layout_height="fill_parent"
tools:context="ex.java.in.fragmentexample.MainActivity">
<fragment
study:id="@+id/fragment1"
study:name="ex.java.in.fragmentexample.Fragment1"
study:layout_width="0px"
study:layout_height="match_parent"
study:layout_weight="1"
/>

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 24 Activity and Multimedia with Databases

<fragment
study:id="@+id/fragment2"
study:name="ex.java.in.fragmentexample.Fragment2"
study:layout_width="0px"
study:layout_height="match_parent"
study:layout_weight="1"
/>
</LinearLayout>
<FrameLayout xmlns:android="url"
xmlns:tools="url"
study:layout_width="match_parent"
study:layout_height="match_parent"
study:background="#F5F5DC"
tools:context="ex.java.in.fragmentexample.Fragment1">
<!-- TODO: Update blank fragment layout -->
<TextView
study:layout_width="match_parent"
study:layout_height="match_parent"
study:text="@string/hello_blank_fragment" />
</FrameLayout>
<FrameLayout xmlns:android="url"
xmlns:tools="url"
study:layout_width="match_parent"
study:layout_height="match_parent"
study:background="#F0FFFF"
tools:context="ex.java.in.fragmentexample.Fragment2">
<!-- TODO: Update blank fragment layout -->
<TextView
study:layout_width="match_parent"
study:layout_height="match_parent"
study:text="@string/hello_blank_fragment" />
</FrameLayout>

package ex.java.in.fragmentexample;
import study.ex;
import study.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
}
}

package ex.java.in.fragmentexample;
import study.os.Bundle;
import study.support.v4.app.Fragment;
import study.view.LayoutInflater;
import study.view.View;

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 25 Activity and Multimedia with Databases

import study.view.ViewGroup;
public class Fragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
package ex.java.in.fragmentexample;
import study.os.Bundle;
import study.support.v4.app.Fragment;
import study.view.LayoutInflater;
import study.view.View;
import study.view.ViewGroup;

public class Fragment2 extends Fragment {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}
}

Output :

Hello blank fragment 1 Hello blank fragment 2

Fig. 5.3.6
5.4 Service
· Service is a component which runs in the background, without direct interaction with the user.
· As the service has no user interface it is not bound to the lifecycle of an activity.
· Services are used for repetitive and potential long running operations, checking for new data, data
processing, indexing content, etc.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 26 Activity and Multimedia with Databases

· There are four different types of Android services :


1. Bound Service - A bound service is a service that has some other component (typically an Activity)
bound to it. A bound service provides an interface that allows the bound component and the
service to interact with each other.
2. IntentService - An IntentService is a specialized subclass of the Service class that simplifies service
creation and usage. An IntentService is meant to handle individual autonomous calls.
3. Started Service - A started service is a service that has been started by some other Android
component (such as an Activity) and is run continuously in the background until something
explicitly tells the service to stop.
4. Hybrid Service - A hybrid service is a service that has the characteristics of a started service and a
bound service. A hybrid service can be started by when a component binds to it or it may be
started by some event.

5.4.1 Android Services Lifecyle Diagram


· Following diagram shows the lifecycle of Started service, when the service created with start Service()
and the lifecycle of Bound service, when the service created with bind Service().

Call to Call to
startService() bindService()

onCreate() onCreate()

onStartCommand() onBind()

Service Clients are bound


running Active to service
lifetime
All clients unbind by calling
The service is stopped unbindService()
by itself or a client
onUnbind()

onDestroy() onDestroy()

Service Service
shut down shut down

Unbounded Bounded
service service

Fig 5.4.1 Android services Life Cycle


· To create a service, we need to create a class that extends a Service base class or one of its existing
subclasses.
· During our service implementation, we must need to override the some of callback methods that
handle the key aspects of service lifecycle and provide the functionality that allow our components to
bind to the service.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 27 Activity and Multimedia with Databases

5.4.2 Features of Service · You can start a service from an activity or other
application component by passing an Intent to start
5.4.2.1 Android Platform Service Service() or start Foreground Service() .
· The Android platform is Google Inc.'s open and free · The Android system calls the service's on Start
software stack that includes an operating system, Command() method and passes it the Intent , which
middleware and also key applications for use on specifies which service to start.
mobile devices, including smartphones. Android is
·A service needs to be declared in the
an Open Handset Alliance Project.
AndroidManifest.xml file and the implementing
What are Services in Android System ? class must extend the Service class or one of its
subclasses.
1) Faceless components : The components of
Android system that run in the background are 5.4.3.1 Create a Service
Service components. They are very much like
· Generally, in android to create a service we must
activities, only without a User Interface.
create a subclass of Service or use one of existing
2) Taking care of long running background tasks : subclass.
They carry out long-running tasks desired by the
· In android the application component such as an
application (without user intervention). Services
activity can start the service by calling start
run the background tasks that do not require a
Service() which results in calling the service's on
User Interface.
Start Command() method.
3) Unaffected by activity switching : Each Service · Following is the simple example of creating a
has a specific job, and they keep at it if you service in android application.
switch between different Activities, or even if
public class SampleService extends Service {
you switch to a different application altogether.
@Override
4) It can also provide functionality to other public int onStartCommand(Intent intent, int flags, int
applications. startId) {
5) Example of Service : A good example is your //TODO write your own code
music player. return Service.START_NOT_STICKY;
} @Override
· When you play music in your Android handset
public IBinder onBind(Intent intent) {
using a playlist, the music player takes care of the
//TODO for communication return IBinder
job itself, without user intervention. You do not
implementation
have to change the song every time one song ends.
return null;
This automation is due to the service component of
}
Android.
}
Service Components in Facebook Application Register a Service in Manifest File
· Talking about Facebook application again, the · Once we create a service, we must need to register
various friend feeds and friendship notifications etc. that isn android manifest file using <service>
are examples of Services. The new friend invites element like as shown below.
always update in the background, whether you <manifest ... >
interact with it or not. ...
<application ... >
5.4.3 Defining New Service <service study:name=".SampleService" />
Starting and defining custom services </application>
· Custom services are started from other Android ...
components, i.e., activities, broadcast receivers and </manifest>
other services.
Start a Service
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 28 Activity and Multimedia with Databases

In android, the component such as an activity, service 2) Bound Service


or receiver can start the service using start Service()
A service is bound when another component (e.g.
method.
client) calls bindService() method. The client can
Following is the sample code snippet of starting a unbind the service by calling the unbindService()
service using start Service method. method.

Intent intent = new Intent(this, MyService.class); The service cannot be stopped until all clients unbind
the service.
startService(intent);

5.4.4 Service Life Cycle Android Services Example

· There can be two forms of a service.The lifecycle of Following is the example of start playing music in
service can follow two different paths : started or background when we start a service and that music
bound. will play continuously until we stop the service in
android application.
1) Started Service
· Create a new android application using android
A service is started when component (like activity) studio and give names as Services. In case if you
calls startService() method, now it runs in the are not aware of creating an app in android studio
background indefinitely. It is stopped by stopService() check this article Android Hello World App.
method. The service can stop itself by calling the
stopSelf() method.

Service is started Service is created


by bindService() by bindService()

onCreate() onCreate()

onStart() onBind()

Service is Client interacts with the service


running
onRebind()

The service
is stopped
(no callback)
onUnbind()

onDestroy() onDestroy()

Service is Service is
shut down shut down

Fig 5.4.2 Service Life Cycle

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 29 Activity and Multimedia with Databases

· Now we need to create our own custom service file MyService.java in \study\ex.services path to
define our actual provider and associated methods
· Once we create a new file MyService.java, open it and write the code like as shown below :
package ex.services;
import android.app.Service;
import study.content.Intent;
import android.media.MediaPlayer;
import study.os.IBinder;
import android.provider.Settings;
import study.widget.Toast;

public class MyService extends Service {


private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
// This will play the ringtone continuously until we stop the service.
player.setLooping(true);
// It will start the player
player.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// Stopping the player when service is destroyed
player.stop();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
Now open act_main.xml file from \src\main\res\layout path and write the following code.
Act_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="url"
study:orientation="vertical" study:layout_width="match_parent"
study:layout_height="match_parent">
<Button
study:id="@+id/btnStart"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 30 Activity and Multimedia with Databases

study:onClick="startService"
study:layout_marginLeft="130dp"
study:layout_marginTop="150dp"
study:text="Start Service"/>
<Button
study:id="@+id/btnstop"
study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:onClick="stopService"
study:layout_marginLeft="130dp"
study:layout_marginTop="20dp"
study:text="Stop Service"/>
</LinearLayout>
Now open MainActivity.java file from \study\ex.services path and write following to implement
custom broadcast intents.
package ex.services;
import study.content.Intent;
import study.ex;
import study.os.Bundle;
import study.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
}
// Start the service
public void startService(View view) {
startService(new Intent(this, MyService.class));
}
// Stop the service
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
}
Now we need to register our service in android manifest file (AndroidManifest.xml) using <service>
attribute like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="url"
package="ex.services">

<application
study:allowBackup="true"
study:icon="@mipmap/ic_launcher"
study:label="@string/app_name"
study:roundIcon="@mipmap/ic_launcher_round"
study:supportsRtl="true"
study:theme="@style/AppTheme">

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 31 Activity and Multimedia with Databases

<activity study:name=".MainActivity">
<intent-filter>
<action study:name="android.intent.action.MAIN" />
<category study:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service study:name=".MyService" />
</application>
</manifest>
Output of Android Service Example
When we run above example in android emulator we will get a result like as shown below

Fig. 5.4.3

If we click on Start Service button, the default ringtone will start playing and it will continue until we
stop the service. This is how we can create, start or stop services in android applications based on our
requirements.

5.4.5 Permissions
· Android uses permission.
· API reference for the manifest tag that declares your app's required permissions.
· Device compatibility : Information about how Android works on different types of devices and an
introduction to how you can optimize your app for each device or restrict your app's availability to
different devices.

5.5 Android System Architecture


See Fig. 5.5.1 on next page.
Android operating system comprise of different software components arranges in stack. Different
components of android operating system are -
1. Linux kernel 2. Libraries 3. Android Run time
4. Application Framework 5. Applications

Linux kernel
1. Bottom layer of android operating system is Linux kernel.
2. Android is built on top of Linux 2.6 Kernel and few architectural changes made by Google.
3. Linux Kernel provides the basic system functionality such as process management, memory
management and device management
4. Linux kernel also provides array of device drivers which make our task easier while interfacing the
android with peripheral devices.

Libraries
1. On the top of Linux Kernel another layer called libraries is present.
2. It provides the different libraries useful for well functioning of android operating system.
3. Libraries are java libraries build specific for android operating system.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 32 Activity and Multimedia with Databases

Applications

Native Android Apps Third Party Apps

Applications Framework

Activity Window Notification View XMPP


Manager Manager Manager System Service

Location Package Resource Content Telephony


Manager Manager Manager Providers Manager

Libraries

SQLite WebKit OpenGL ES Android Runtime

Core
Surface Media Libraries
FreeType
Manager Framework
Dalvik Virtual
SSL SGL libc Machine

Linux kernel

Display Wifi Audio Binder (IPC) Bluetooth


Driver Driver Drivers Drivers Driver

Camera Power Process Memory Flash Memory


Driver Management Management Management Driver

Fig. 5.5.1 Android System Architecture

Some of the libraries are listed below -

Libraries Explanation
SQLite It is used to access data published by content providers and includes SQLite database management
classes
SSL It is used to provide internet security
OpenGL It is used to provide Java interface to the OpenGL/ES 3D graphics rendering API.
Media framework It is used to provides different media codecs which allow the recording and playback of different
media formats
WebKit It is the browser engine used to display internet content or HTML content

Android Runtime
1. It is third component of the android architecture and placed in second layer from bottom
2. It provides most important part of android called Dalvik Virtual Machine.
3. Dalvik Virtual Machine is similar to JVM but only difference is that it is designed and optimized
for Android.
4. Dalvik Virtual machine uses core functions of Linux such as memory management and
multithreading and enables each android app to run its own process.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 33 Activity and Multimedia with Databases

Application framework 2. All this top layer you will find all the
1. It is 2nd topmost component in android operating applications that comes along with your android
system stack device like phone, contacts, web browsers,
2. Android applications directly interacts with Camera etc. This layer shows all the applications
application framework. developed by you.
3. Application framework manages the basic
5.5.1 Multimedia Framework
functions of android device such as resource
management, voice call management etc · The Android multimedia framework includes
Important blocks of Application framework are : support for playing variety of common media types,
so that you can easily integrate audio, video and
Block Explanation images into your applications. (Refer Fig. 5.5.2)
Activity Block is used to manage complete · As the name suggests, Android multimedia
Manager activity life cycle of applications framework is used for playing media files. You can
Content Block is used to manage the data use the Media Player API to play an audio or a
Providers sharing between two applications video file :
Telephony Block is used to manages all voice 1. From your application's resources.
Manager calls
2. From standalone files (using internal URIs).
Location Block is used to manage the
Manager Locations obtained using GPS or cell 3. From a stream over a network connection (using
tower URLs).
Resource Block is used to manage the
Manager different types of resources used in 5.5.2 Play Audio and Video
android app · Android supports the playing of audio and video
Applications through the Media Player class.
1. Applications created by third party users or · The Media Player class is at the heart of the
developer will be installed on application layer. Android media package.

Camera Media recoder Media player


Java
Aplication

android,hardware,Camera android,media,MediaRecorder android,media,MediaPlayer android,view,Surface


Java
Framework

mediarecorder

Camera mediaplayer

Audio
MediaPlayer Service Filnger
Camera Service
Surface
UI lib Filnger
Midi Vorbis libaudio
Camera PV Author PVPlayer Player Player
Hardware Alsa lib
Packet Video Framework
Native

Driver V412
Capture Hardware Codes Main Video Audio
framebuffer Plane (Alsa)

Fig. 5.5.2 Android Multimedia Framework

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 34 Activity and Multimedia with Databases

· Apart from the Media Player class, the Sound Pool Playing Audio from file-system
and Jet Player classes are also provided to be used · SoundPool Class load (String path, int priority)
to play audio files. method is used to load the audio file from raw
folder. If you want to load a sound from the raw
5.5.2.1 Playing Audio Files resource file "bigwave.mp3", you would specify
· Media Player is the most widely used class for "R.raw.bigwave" as the resource ID. This returns the
playing media files. integer SoundID that can be use to play the sound.
· Media Player has been designed to play large audio
files and streams also supporting playback ToneGenerator or Stream
operations like stop, start, pause etc and seeking · This class provides methods to play DTMF tones,
operations. call supervisory tones and proprietary tones.
· It also supports listeners related to the media · The ToneGenerator object requires an output stream
operations. type and volume. startTone() is used to play the
· Playing of audio and video in MediaPlayer can be tone. startTone() method starts the playback of a
done through the following ways : tone of the specified type for the specified duration.
n Playing from raw resource.
//Output Stream Type and Volume
n Playing from file-system.
ToneGenerator tg=new
n Playing from stream. ToneGenerator(AudioManager.STREAM_RING, 100);
//Play Tone
Playing Audio from resourse
tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT);
· This is the most common way of playing audio
files. 5.5.2.2 Playing Video Files
· In this case the audio file should be present in the · Android provides a specialized view control
raw or assets folder of the project like the one study.widget.
shown in Fig. 5.5.3.
· VideoView that encapsulates creating and
initializing the MediaPlayer.
· The VideoView class can load images from various
sources (such as resources or content providers),
and takes care of computing its measurement from
the video so that it can be used in any layout
manager, also providing various display options
such as scaling and tinting.
· VideoView can be used to display video files
present in SDCard FileSystem or files present
online.
· MediaPlayer class provides a different type of
methods to control audio and video files based on
requirements.

5.5.3 Text to Speech


· Text to speech is becoming an integral part of many
content driven mobile APPs.
· If your APP is a tutorial or content heavy, then it is
high time you think about adding the
Text-To-Speech (TTS) feature to it.
Fig 5.5.3 Raw folder media files
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 35 Activity and Multimedia with Databases

· Voice input based command and text to speech is a study:text="Enter Text to Speak"/>
trend now. In this tutorial, we will explore how <EditText
"Text-To-Speech(TTS)" feature can be implemented study:id="@+id/txtSpeak"
in an Android APP. study:layout_width="wrap_content"
study:layout_height="wrap_content"
· Text to speech (TTS) makes an android device read
study:layout_marginLeft="100dp"
the text and convert it to audio out via the speaker.
study:ems="10"/>
Android TTS supports multiple languages.
<Button
· TTS is a simple but powerful feature. study:id="@+id/btnSpeech"
· It can also be effectively used in mobile APPs study:layout_width="wrap_content"
dedicated to visually impaired people or in study:layout_height="wrap_content"
educational app for kids or can be used in study:layout_marginLeft="100dp"
pronunciation learning app, etc. These are some of study:text="Speak" />
the ways you can use TTS. </LinearLayout>
Now open your main activity file MainActivity.java
· Using TextToSpeech enhances interaction between
from \study\ex.textspeechexample path and write the
the user and the mobile application.
code like as shown below
· Android TTS was available from version 1.6.
package ex.textspeechexample;
· It has features to control speed, pitch of speech as import study.os.Build;
well as type of language. We will also learn to use import android.speech.tts.TextToSpeech;
these features in this tutorial. import study.ex;
· TextToSpeech needs to be initialized first. For this, import study.os.Bundle;
you need to implement the TextToSpeech. import study.util.Log;
OnInitListener interface and override the method : import study.view.View;
onInit. import study.widget.Button;
Example : TextToSpeech tts = new TextToSpeech(this, import study.widget.EditText;
import java.util.Locale;
this)

Android TextToSpeech Example public class MainActivity extends AppCompatActivity


implements TextToSpeech.OnInitListener {
· Following is the example of converting the given
Button speakBtn;
text to voice using android TextToSpeech object.
EditText speakText;
· Create a new android application using android
TextToSpeech textToSpeech;
studio and give names as TextSpeechExample. In @Override
case if you are not aware of creating an app in protected void onCreate(Bundle savedInstanceState) {
android studio check this article Android Hello super.onCreate(savedInstanceState);
World App. setContentView(R.layout.act_main);
speakText = (EditText) findViewById(R.id.txtSpeak);
<?xml version="1.0" encoding="utf-8"?> speakBtn = (Button)findViewById(R.id.btnSpeech);
<LinearLayout xmlns:android="url" textToSpeech = new TextToSpeech(this, this);
study:orientation="vertical" speakBtn.setOnClickListener(new
study:layout_width="match_parent" View.OnClickListener() {
study:layout_height="match_parent"> @Override
<TextView public void onClick(View v) {
study:id="@+id/fstTxt" texttoSpeak();
study:layout_width="wrap_content" }
study:layout_height="wrap_content" });
study:layout_marginLeft="100dp" }
study:layout_marginTop="150dp" @Override
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 36 Activity and Multimedia with Databases

public void onInit(int status) { 5.5.4 Sensors


if (status == TextToSpeech.SUCCESS) {
· Sensors can be used to monitor the
int result = textToSpeech.setLanguage(Locale.US);
three-dimensional device movement or change in
if (result == TextToSpeech.LANG_MISSING_DATA
the environment of the device.
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported"); · Android provides sensor api to work with different
} else { types of sensors.
texttoSpeak(); · Android Sensors contains properties to detect
} changes in the environment such as light, proximity,
} else { rotation, movements, magnetic fields and much
Log.e("error", "Failed to Initialize"); more.
}
· Android sensors can be divided into the following
}
categories :
@Override
public void onDestroy() {
n Environmental sensors. These measure
if (textToSpeech != null) { environmental conditions, such as air
textToSpeech.stop(); temperature, pressure, humidity and ambient
textToSpeech.shutdown(); light levels.
} n Position sensors. This category includes sensors
super.onDestroy(); that measures the device's physical position,
}
such as proximity sensors and geomagnetic field
private void texttoSpeak() {
sensors.
String text = speakText.getText().toString();
if ("".equals(text)) { Motion sensors. These sensors measure device
n

text = "Please enter some text to speak."; motion, and include accelerometers, gravity
} sensors, gyroscopes, and rotation vector sensors.
if (Build.VERSION.SDK_INT >= · In addition, sensors can either be :
Build.VERSION_CODES.LOLLIPOP) { n Hardware based. These are physical components
textToSpeech.speak(text,
that are built into the device and directly
TextToSpeech.QUEUE_FLUSH, null, null);
measure specific properties, such as acceleration
}
or the strength of the surrounding geomagnetic
else {
textToSpeech.speak(text,
fields.
TextToSpeech.QUEUE_FLUSH, null); Software based, sometimes known as virtual
n

} sensors or composite sensors. These typically


} collate data from multiple hardware-based
} sensors. Towards the end of this article, we'll be
If you observe above code, we are converting the text working with the rotation vector sensor, which
to speech conversion using Text To Speech class. is a software sensor that combines data from the
Output of Android TextToSpeech Example device's accelerometer, magnetometer, and
gyroscope.
· Some of the sensors are hardware based and some
Enter text to speak are software based sensors. Whatever the sensor is,
Hello android allows us to get the raw data from these
sensors and use it in our application. For this
SPEAK
android provides us with some classes.

Fig. 5.5.4

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 37 Activity and Multimedia with Databases

· Android Sensor API


n SensorManager
Is the Android system service that gives an app access to hardware sensors.
n Sensor
Is the Android representation of a hardware sensor on a device.
n SensorEventListener
Is an interface that provides the callbacks to alert an app to sensor-related events.
n SensorEvent
Is the data structure that contains the information that is passed to an app when a hardware sensor
has information to report.

Sensor Type Description Common Uses

TYPE_ACCELEROMETER Hardware Measures the acceleration force in Motion detection


2
m/s that is applied to a device on all (shake, tilt, etc.).
three physical axes (x, y, and z),
including the force of gravity.

TYPE_AMBIENT_TEMPERATURE Hardware Measures the ambient room temperature Monitoring air


in degrees Celsius (°C). temperatures.

TYPE_GRAVITY Software Measures the force of gravity in Motion detection


2
or m/s that is applied to a device on all (shake, tilt, etc.).
Hardware three physical axes (x, y, z).

TYPE_GYROSCOPE Hardware Measures a device's rate of rotation in Rotation detection


rad/s around each of the three physical (spin, turn, etc.).
axes (x, y, and z).

TYPE_LIGHT Hardware Measures the ambient light level Controlling screen


(illumination) in lx. brightness.

TYPE_LINEAR_ACCELERATION Software Measures the acceleration force in Monitoring


2
or m/s that is applied to a device on all acceleration along a
Hardware three physical axes (x, y, and z), single axis.
excluding the force of gravity.

TYPE_MAGNETIC_FIELD Hardware Measures the ambient geomagnetic field Creating a compass.


for all three physical axes (x, y, z) in mT.

TYPE_ORIENTATION Software Measures degrees of rotation that a Determining device


device makes around all three physical position.
axes (x, y, z). As of API level 3 you can
obtain the inclination matrix and
rotation matrix for a device by using
the gravity sensor and the geomagnetic
field sensor in conjunction with
the getRotationMatrix() method.

TYPE_PRESSURE Hardware Measures the ambient air pressure in Monitoring air


hPa or mbar. pressure changes.

TYPE_PROXIMITY Hardware Measures the proximity of an object in Phone position


cm relative to the view screen of a during a call.
device. This sensor is typically used to
determine whether a handset is being
held up to a person's ear.

TYPE_RELATIVE_HUMIDITY Hardware Measures the relative ambient humidity Monitoring


in percent (%). dewpoint, absolute,
and relative
humidity.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 38 Activity and Multimedia with Databases

TYPE_ROTATION_VECTOR Software Measures the orientation of a device by Motion detection


or providing the three elements of the and rotation
Hardware device's rotation vector. detection.

TYPE_TEMPERATURE Hardware Measures the temperature of the device Monitoring


in degrees Celsius (°C). This sensor temperatures.
implementation varies across devices
and this sensor was replaced with
the TYPE_AMBIENT_TEMPERATURE
sensor in API Level 14
Table 5.5.1 Sensor types supported by the Android platform

5.5.5 Async Tasks


· Android Async Task is an abstract class provided by Android which gives us the liberty to perform
heavy tasks in the background and keep the UI thread light thus making the application more
responsive.
· Android application runs on a single thread when launched.
· Due to this single thread model tasks that take longer time to fetch the response can make the
application non-responsive.
· To avoid this we use android Async Task to perform the heavy tasks in background on a dedicated
thread and passing the results back to the UI thread.
· Hence use of Async Task in android application keeps the UI thread responsive at all times.
· The basic methods used in an android Async Task class are defined below :
n doInBackground() : This method contains the code which needs to be executed in background. In
this method we can send results multiple times to the UI thread by publishProgress() method. To
notify that the background processing has been completed we just need to use the return
statements
n onPreExecute() : This method contains the code which is executed before the background
processing starts
n onPostExecute() : This method is called after doInBackground method completes processing. Result
from doInBackground is passed to this method
n onProgressUpdate() : This method receives progress updates from doInBackground method, which
is published via publishProgress method, and this method can use this progress update to update
the UI thread
n The three generic types used in an android AsyncTask class are given below :
¡ Params : The type of the parameters sent to the task upon execution

¡ Progress : The type of the progress units published during the background computation

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 39 Activity and Multimedia with Databases

¡ Result : The type of the result of the background computation

5.6 Audio Capture

· Android has a built in microphone through which you can capture audio and store it , or play it in
your phone.
· There are many ways to do that but the most common way is through Media Recorder class. Android
provides MediaRecorder class to record audio or video.
· Android provides MediaRecorder class to record audio or video.
· In order to use MediaRecorder class, you will first create an instance of MediaRecorder class. Its
syntax is given below.
MediaRecorder myAudioRecorder = new MediaRecorder();
Now you will set the source , output and encoding format and output file. Their syntax is given below.
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);

5.6.1 Camera
· Camera is mainly used to capture picture and video. We can control the camera by using methods of
camera api.
· The Android framework provides the facility of working with Camera in two ways :
1. By using existing camera application
2. By using Camera Api
1. Using camera by using camera application : We can capture pictures without using the instance of
Camera class. Here you will use an intent action type of MediaStore.ACTION_IMAGE_CAPTURE
to launch an existing Camera application on your phone. In Android MediaStore is a type of
DataBase which stores pictures and videos in android.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
2. Using Camera By using Camera Api : This class is used for controlling device cameras. It can be
used to take pictures when you are building a camera application.
Camera API works in following ways :

1. Camera Manager : This is used to get all the cameras available in the device like front camera back
camera each having the camera id.
2. CameraDevice : You can get it from Camera Manager class by its id.
3. CaptureRequest: You can create a capture request from camera device to capture images.
4. CameraCaptureSession : To get capture request's from Camera Device create a
CameraCaptureSession.
5. CameraCaptureSession.CaptureCallback : This is going to provide the Capture session results.
Understanding basic classes of Camera Intent and API There are mainly four classes that we are going to discuss.

1. Intent : By the help of 2 constants of MediaStore class, we can capture picture and video without using the
instance of Camera class.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 40 Activity and Multimedia with Databases

1. ACTION_IMAGE_CAPTURE package ex.cameraexample;


import study.content.Intent;
2. ACTION_VIDEO_CAPTURE
import android.graphics.Bitmap;
2. Camera : It is main class of camera api, that can import android.provider.MediaStore;
be used to take picture and video. import study.ex;
3. SurfaceView : It represents a surface view ore import study.os.Bundle;
preview of live camera. import study.view.View;
import study.widget.Button;
4. MediaRecorder : It is used to record video using
import study.widget.ImageView;
camera. It can also be used to record audio files
import study.widget.Toast;
as we have seen in the previous example of
media framework.
public class MainActivity extends AppCompatActivity {
private Button btnCapture;
Android Camera App Example
private ImageView imgCapture;
Following is the example of using an existing camera private static final int Image_Capture_Code = 1;
app in our android applications to capture the photos @Override
on button click. protected void onCreate(Bundle savedInstanceState) {
· Create a new android application using android super.onCreate(savedInstanceState);
studio and give names as CameraExample. In case setContentView(R.layout.act_main);
if you are not aware of creating an app in android btnCapture
studio check this article Android Hello World App. =(Button)findViewById(R.id.btnTakePicture);
imgCapture = (ImageView)
· Once we create an application, open act_main.xml
findViewById(R.id.capturedImage);
file from \res\layout folder path and write the code
btnCapture.setOnClickListener(new
like as shown below.
View.OnClickListener() {
<?xml version="1.0" encoding="utf-8"?> @Override
<RelativeLayout xmlns:android="url" public void onClick(View v) {
study:layout_width="match_parent" Intent cInt = new
study:layout_height="match_parent" Intent(MediaStore.ACTION_IMAGE_CAPTURE);
study:paddingLeft="10dp"
study:paddingRight="10dp"> startActivityForResult(cInt,Image_Capture_Code);
<Button }
study:id="@+id/btnTakePicture" });
study:layout_width="wrap_content" }
study:layout_height="wrap_content" @Override
study:text="Take a Photo" protected void onActivityResult(int requestCode, int
study:textStyle="bold" resultCode, Intent data) {
study:layout_centerHorizontal="true" if (requestCode == Image_Capture_Code) {
study:layout_alignParentBottom="true" /> if (resultCode == RESULT_OK) {
<ImageView Bitmap bp = (Bitmap)
study:layout_width="fill_parent" data.getExtras().get("data");
study:layout_height="fill_parent" imgCapture.setImageBitmap(bp);
study:id="@+id/capturedImage" } else if (resultCode == RESULT_CANCELED) {
study:layout_above="@+id/btnTakePicture"/> Toast.makeText(this, "Cancelled",
</RelativeLayout> Toast.LENGTH_LONG).show();
} } }
Now open your main activity file MainActivity.java from }
\study\ex.cameraexample path and write the code like as
shown below Output of Android Camera App Example

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 41 Activity and Multimedia with Databases

When we click on Take a Photo button, the camera the discoverable devices using a service discovery
will start and we can take the picture of whatever we process.
want, the captured image will be shown in defined · Once the device accepts the pairing request, the two
imageview. devices will exchange a security keys to complete
the bonding process and the devices will cache
5.7 Bluetooth these security keys for later use.
· Once the pairing and bonding process completes,
the devices are ready to exchange the required
information.
· When the session is complete, the device that
initiated the pairing request will release the channel
that linked to the discoverable device.
· The two devices remain bonded, so they can
reconnect automatically during a future session as
long as they're in the range of each other.

Android Bluetooth API


Fig. 5.6.1 · The android.bluetooth package provides a lot of
· The Android platform includes support for the interfaces classes to work with bluetooth such as :
Bluetooth network stack, which allows a device to n BluetoothAdapter
wirelessly exchange data with other Bluetooth n BluetoothDevice
devices.
n BluetoothSocket
· The application framework provides access to the
n BluetoothServerSocket
Bluetooth functionality through the Android
Bluetooth APIs. n BluetoothClass

· These APIs let applications wirelessly connect to n BluetoothProfile


other Bluetooth devices, enabling point-to-point and n BluetoothProfile.ServiceListener
multipoint wireless features. n BluetoothHeadset
· Using the Bluetooth APIs, an Android application
n BluetoothA2dp
can perform the following :
n BluetoothHealth
n Scan for other Bluetooth devices
n BluetoothHealthCallback
n Query the local Bluetooth adapter for paired
Bluetooth devices n BluetoothHealthAppConfiguration
· The Android Bluetooth API provides
n Establish RFCOMM channels
implementations for the following Bluetooth
n Connect to other devices through service profiles :
discovery n Headset. The Headset profile provides support
n Transfer data to and from other devices for Bluetooth headsets to be used with mobile
n Manage multiple connections phones. Android provides the BluetoothHeadset
· To transfer the data between two Bluetooth devices, class, which is a proxy for controlling the
first they must establish a communication channel Bluetooth Headset Service.
using pairing process. n A2DP. The Advanced Audio Distribution Profile
· The devices which we are going to pair must be (A2DP) profile defines how high quality audio
discoverable and should accept the incoming can be streamed from one device to another
connection requests. Generally, the devices will find over a Bluetooth connection.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 42 Activity and Multimedia with Databases

n Health Device. Android 4.0 (API level 14) study:layout_marginTop="28dp"


introduces support for the Bluetooth Health study:text="TURN_OFF" />
Device Profile (HDP). This lets you create </RelativeLayout>
Provide Permission
applications that use Bluetooth to communicate
You need to provide following permissions in
with health devices that support Bluetooth, such
AndroidManifest.xml file.
as heart-rate monitors, blood meters,
<uses-permission
thermometers, scales, and so on. For a list of study:name="android.permission.BLUETOOTH" />
supported devices and their corresponding <uses-permission
device data specialization codes, refer to study:name="android.permission.BLUETOOTH_ADMIN" />
Bluetooth's HDP Device Data Specializations.
<?xml version="1.0" encoding="utf-8"?>
Android Bluetooth Example :
<manifest xmlns:androclass="url"
Enable, disable and make discovrable bluetooth package="my.example.bluetooth"
programmatically study:versionCode="1"
study:versionName="1.0" >
<RelativeLayout xmlns:androclass="url" <uses-sdk
xmlns:tools="url" study:minSdkVersion="8"
study:layout_width="match_parent" study:targetSdkVersion="16" />
study:layout_height="match_parent" <uses-permission
tools:context=".MainActivity" > study:name="android.permission.BLUETOOTH" />
<TextView study:text="" <uses-permission
study:id="@+id/out" study:name="android.permission.BLUETOOTH_ADMIN" />
study:layout_width="wrap_content"
study:layout_height="wrap_content"> <application
</TextView> study:allowBackup="true"
<Button study:icon="@drawable/ic_launcher"
study:id="@+id/button1" study:label="@string/app_name"
study:layout_width="wrap_content" study:theme="@style/AppTheme" >
study:layout_height="wrap_content" <activity
study:layout_alignParentLeft="true" study:name="my.example.bluetooth.MainActivity"
study:layout_alignParentTop="true" study:label="@string/app_name" >
study:layout_marginLeft="30dp" <intent-filter>
study:layout_marginTop="49dp" <action
study:text="TURN_ON" /> study:name="android.intent.action.MAIN" />
<Button <category
study:id="@+id/button2" study:name="android.intent.category.LAUNCHER" />
study:layout_width="wrap_content" </intent-filter>
study:layout_height="wrap_content" </activity>
study:layout_alignLeft="@+id/button1" </application>
study:layout_below="@+id/button1" </manifest>
study:layout_marginTop="27dp"
study:text="DISCOVERABLE" /> Code to enable, disable and make bluetooth discoverable.
<Button
study:id="@+id/button3" package my.example.bluetooth;
study:layout_width="wrap_content" import study.os.Bundle;
study:layout_height="wrap_content" import android.app.Activity;
study:layout_alignLeft="@+id/button2" import study.view.Menu;
study:layout_below="@+id/button2" import android.app.Activity;

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 43 Activity and Multimedia with Databases

import android.bluetooth.BluetoothAdapter; Toast.makeText(getApplicationContext(),


import study.content.Context; "MAKING YOUR DEVICE DISCOVERABLE",
import study.content.Intent; Toast.LENGTH_LONG);
import study.os.Bundle; Intent enableBtIntent = new Intent
import study.util.Log; (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
import study.view.View; startActivityForResult(enableBtIntent,
import study.widget.Button; REQUEST_DISCOVERABLE_BT);
import study.widget.TextView;
import study.widget.Toast; }
}
public class MainActivity extends Activity { });
private static final int REQUEST_ENABLE_BT = 0; button3.setOnClickListener(new View.OnClickListener()
private static final int REQUEST_DISCOVERABLE_BT {
= 0; @Override
public void onClick(View arg0) {
@Override mBluetoothAdapter.disable();
protected void onCreate(Bundle savedInstanceState) { //out.append("TURN_OFF BLUETOOTH");
super.onCreate(savedInstanceState); Toast.makeText(getApplicationContext(), "TURNING_OFF
setContentView(R.layout.act_main); BLUETOOTH", Toast.LENGTH_LONG); }
final TextView out=(TextView)findViewById(R.id.out); });
final Button button1 = (Button) }
findViewById(R.id.button1); @Override
final Button button2 = (Button) public boolean onCreateOptionsMenu(Menu menu) {
findViewById(R.id.button2); // Inflate the menu; this adds items to the action bar
final Button button3 = (Button) if it is present.
findViewById(R.id.button3); getMenuInflater().inflate(R.menu.act_main, menu);
final BluetoothAdapter mBluetoothAdapter = return true;
BluetoothAdapter.getDefaultAdapter(); }
if (mBluetoothAdapter == null) { }
out.append("device not supported");
} 5.7.1 Animation
button1.setOnClickListener(new View.OnClickListener() · Animation is a method in which pictures are
{ manipulated to appear as moving images.
public void onClick(View v) {
· So, we can think of animations as moving images.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new · For example, if you want to do some UI change in
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); your application and if you change the UI directly
startActivityForResult(enableBtIntent, then it will look very ugly.
REQUEST_ENABLE_BT); · Android Animation is used to give the UI a rich
} look and feel.
} · Animations in android apps can be performed
});
through XML or android code.
button2.setOnClickListener(new View.OnClickListener()
· Animation in android apps is the process of
{
@Override
creating motion and shape change.
public void onClick(View arg0) { · The basic ways of animation :
if (!mBluetoothAdapter.isDiscovering()) { 1. Fade In Animation
//out.append("MAKING YOUR DEVICE
2. Fade Out Animation
DISCOVERABLE");

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 44 Activity and Multimedia with Databases

3. Cross Fading Animation Follow the best steps :


4. Blink Animation
Step 1 : Open Android Studio and create a new
5. Zoom In Animation
project with Empty Activity template.
6. Zoom Out Animation
Step 2 : After creating the project, the very first
7. Rotate Animation
thing that you have to do is making an anim
8. Move Animation
resource directory where you can store all your
9. Slide Up Animation animation files. So, go to res directory and right click
10. Slide Down Animation on it, then click on New > Android Resource
11. Bounce Animation Directory and after that choose resource type as anim
12. Sequential Animation and then click on OK.

13. Together Animation Step 3 : Now, you have to create some Animation
files in the anim folder that you have created in the
Basic Animation using XML
previous step. So, right click on res/anim and select
· The best part about animation that I like is the fact
New > Animation Resource File and then enter the
that you can use animation just by writing some
XML code. Yeah and this is the need because in file name and click on OK. Here, we will see how to
Animation, you are dealing with the UI part and in use the Fade In animation. So, my file name is
order to have Animation, XML codes can be used. fade_in.xml.
· In order to have a thorough knowledge of Step 4 : Our next step is to add the animation that
Animation, you should know some of the important
we want to perform in the file that we have added
XML attributes that can be used in your application
in the previous step. Add the below code for Fade In
to have a perfect Animation. Some of these
attributes are : animation in your fade_in.xml file :

1. study:duration : It is used to specify the


<?xml version="1.0" encoding="utf-8"?>
duration of animation i.e. how long a particular
<set xmlns:android="url"
Animation will continue.
study:fillAfter="true">
2. study:interpolator : It is used to define the rate <alpha
of change of Animation i.e. how fast a particular study:duration="5000"
UI will change to another UI. study:fromAlpha="0.0"
3. study:startOffset : When you are having a
number of animations one after the other, then study:interpolator="@study:anim/accelerate_interpolator"
you have to specify some time to a particular study:toAlpha="1.0" />
animation and that animation will wait for that </set>
duration and after that, it will start. Step 5 : Add the UI for the MainActivity. Here we
4. study:repeatMode : This is used to repeat a will add the desired UI of the MainActivity. Here, I
particular animation. am adding one TextView (to apply animation on)
5. study:repeatCount : This is used to specify the and one Button(to start the animation).
repeat count of a particular animation. You can
set the repeat count of an animation to be <?xml version="1.0" encoding="utf-8"?>
infinite, if you want infinite repetition. <androidx.constraintlayout.widget.ConstraintLayout
Now, we are done with the introduction part. Let's xmlns:android="url"
implement some basic animations in our project.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 45 Activity and Multimedia with Databases

xmlns:tools="url" applicationContext,
xmlns:app="ex/apk/res-auto" R.anim.fade_in)
study:layout_width="match_parent" //handling aniamtion on button click
study:layout_height="match_parent" btn.setOnClickListener {
tools:context=".MainActivity"> txtMessage.setVisibility(View.VISIBLE)
<TextView // starting the animation
study:id="@+id/text" txtMessage.startAnimation(animFadein)
study:layout_width="wrap_content" }
study:layout_height="wrap_content" }
study:text="Hello World!" }
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
loadAnimation() method is used to load the desired
app:layout_constraintRight_toRightOf="parent"
animation i.e. in our case, it is fade_in.xml file.
app:layout_constraintTop_toTopOf="parent"/>
<Button startAnimation() method is used to start an animation
study:id="@+id/btn" on a particular component. If you want to perform
study:layout_width="wrap_content" some operations before, after or during the
study:layout_height="wrap_content" Animation, then you can implement the
app:layout_constraintTop_toBottomOf="@+id/text" AnimationListener in your call and then override the
app:layout_constraintEnd_toEndOf="parent" below function for the same :
study:layout_marginEnd="8dp"
study:layout_marginRight="8dp" 1. onAnimationStart(): Will be called when the
app:layout_constraintStart_toStartOf="parent" Animation will start.
study:layout_marginLeft="8dp" 2. onAnimationEnd(): Will be called when the
study:layout_marginStart="8dp" Animation will end.
study:layout_marginBottom="8dp"
3. onAnimationRepeat(): Will be called when you
app:layout_constraintBottom_toBottomOf="parent"
repeat an Animation.
study:text="Click Me"/>
</studyx.constraintlayout.widget.ConstraintLayout> All you need to do is implement the
AnimationListener and then set the animation
Step 6 : After adding the UI, our last step is to listener. Our final code after implementing the
connect the animation when the Button is clicked. So, AnimationListener will be :
the code of MainActivty.kt file looks like : class MainActivity : AppCompatActivity(),
Animation.AnimationListener {
class MainActivity : AppCompatActivity() {
//TextView
//TextView lateinit var txtMessage: TextView
lateinit var txtMessage: TextView //Button
//Button lateinit var btn: Button
lateinit var btn: Button // Animation
// Animation lateinit var animFadein: Animation
lateinit var animFadein: Animation override fun onCreate(savedInstanceState: Bundle?) {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)
super.onCreate(savedInstanceState) setContentView(R.layout.act_main)
setContentView(R.layout.act_main) txtMessage = findViewById<TextView>(R.id.text)
txtMessage = findViewById<TextView>(R.id.text) btn = findViewById<Button>(R.id.btn)
btn = findViewById<Button>(R.id.btn) //loading Animation
//loading Animation animFadein = AnimationUtils.loadAnimation(
animFadein = AnimationUtils.loadAnimation( applicationContext,
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 46 Activity and Multimedia with Databases

R.anim.fade_in) study:toDegrees="360"
//set animation listener study:pivotX="50%"
animFadein.setAnimationListener(this) study:pivotY="50%"
//handling aniamtion on button click study:duration="5000" >
btn.setOnClickListener { </rotate>
txtMessage.setVisibility(View.VISIBLE) <rotate xmlns:android="url"
// starting the animation study:startOffset="5000"
txtMessage.startAnimation(animFadein) study:fromDegrees="360"
} study:toDegrees="0"
} study:pivotX="50%"
override fun onAnimationRepeat(p0: Animation?) { study:pivotY="50%"
//To change body of created functions use File | study:duration="5000" >
Settings | File Templates. </rotate>
} </set>
override fun onAnimationEnd(p0: Animation?) {
//To change body of created functions use File |
Settings | File Templates.
Animation for Blink
<?xml version="1.0" encoding="utf-8"?>
}
<set xmlns:android="url">
override fun onAnimationStart(p0: Animation?) {
<alpha study:fromAlpha="0.0"
//To change body of created functions use File |
study:toAlpha="1.0"
Settings | File Templates.
}
study:interpolator="@study:anim/accelerate_interpolator"
}
study:duration="600"
study:repeatMode="reverse"
Run your application on mobile device and see the study:repeatCount="infinite"/>
Animation. </set>

In the next part of this section, we will look upon


some basic animations XML file. You can use these Animation for Zoom In
animations in the same manner as used in the above <?xml version="1.0" encoding="utf-8"?>
example. Add the below files in your anim folder. <set xmlns:android="url"
study:fillAfter="true" >
<scale
Animation for Fade Out xmlns:android="url"
<?xml version="1.0" encoding="utf-8"?> study:duration="1000"
<set xmlns:android="url" study:fromXScale="1"
study:fillAfter="true" > study:fromYScale="1"
<alpha study:pivotX="50%"
study:duration="5000" study:pivotY="50%"
study:fromAlpha="1.0" study:toXScale="3"
study:interpolator="@study:anim/accelerate_interpolator" study:toYScale="3" >
study:toAlpha="0.0" /> </scale>
</set> </set>

Animation for ClockWise rotation


<?xml version="1.0" encoding="utf-8"?> Animation for Zoom out
<set xmlns:android="url"> <?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="url" <set xmlns:android="url"
study:fromDegrees="0" study:fillAfter="true" >

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 47 Activity and Multimedia with Databases

<scale · SQLite is a open source SQL database that stores


xmlns:android="url" data to a text file on a device. Android comes in
study:duration="1000" with built in SQLite database implementation.
study:fromXScale="1.0"
· SQLite supports all the relational database features.
study:fromYScale="1.0"
· In order to access this database, you don't need to
study:pivotX="50%"
study:pivotY="50%" establish any kind of connections for it like
study:toXScale="0.5" JDBC,ODBC e.t.c.
study:toYScale="0.5" > · Android SQLite is a very lightweight database
</scale> which comes with Android OS.
</set> · Android SQLite combines a clean SQL interface
with a very small memory footprint and decent
Animation for MoveTo move one component form speed.
one position to other · SQLite is used as a database for android application
<set development.
xmlns:android="url"
study:interpolator="@study:anim/linear_interpolator" Database - Creation
study:fillAfter="true"> · In order to create a database you just need to call
<translate this method open Or Create Database with your
study:fromXDelta="0%p" database name and mode as a parameter. It returns
study:toXDelta="75%p" an instance of SQLite database which you have to
study:duration="800" /> receive in your own object. Its syntax is given
</set> below
· SQLiteDatabase mydatabase =

Animation for Bounce openOrCreateDatabase ("your database name",


<?xml version="1.0" encoding="utf-8"?> MODE_PRIVATE,null);
<set xmlns:android="url"
Role of SQLite Database in Android
study:fillAfter="true"
· SQLite is an open source and lightweight database
administration system that takes a small amount of
study:interpolator="@study:anim/bounce_interpolator">
disk storage so it is an excellent choice of
<scale
developers to develop a new application for
study:duration="500"
Android. It is the first choice of developers because
study:fromXScale="1.0"
study:fromYScale="0.0" n Zero configuration database
study:toXScale="1.0" n Don't have server
study:toYScale="1.0" />
n Open source
</set>
n Single file database
5.8 SQLite Database Four Major things to understand about SQLite :
· SQLite is an open-source relational database i.e. 1. SQLite is RDBMS (Relational Database
used to perform database operations on android Management System)
devices such as storing, manipulating or retrieving 2. SQLite is written in C programming language
persistent data from the database.
· It is embedded in android by default. So, there is
no need to perform any database setup or
administration task.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 48 Activity and Multimedia with Databases

3. SQLite is embedded within the Android 5.8.3 Extracting Value from Cursor
operating System, so you don't need anything · The SQLite Database always presents the results as
external on Android to use SQLite a Cursor in a table format that resembles that of a
4. To manipulate data (insert, update, delete) in SQL database.
SQLite database - we'll use SQL (Structured · Cursors are what contain the result set of a query
Query Language) made against a database in Android.
· The Cursor class has an API that allows an app to
5.8.1 Necessity of SQLite Database
read (in a type-safe manner) the columns that were
· SQLite is an open-source relational database i.e.
returned from the query as well as iterate over the
used to perform database operations on android
rows of the result set.
devices such as storing, manipulating or retrieving
· The basic purpose of a cursor is to point to a single
persistent data from the database.
row of the result fetched by the query.
· It is embedded in android bydefault. So, there is no
· You can think of the data as an array of rows.
need to perform any database setup or
administration task. · A cursor is a pointer into one row of that structured
data.
5.8.2 Creation and Connection of the Database · The Cursor class provides methods for moving the
1. At a shell or DOS prompt, enter: "sqlite3 test.db". cursor through the data structure, and methods to
This will create a new database named "test.db". get the data from the fields in each row.
(You can use a different name if you like.) · The Cursor class has a number of subclasses that
2. Enter SQL commands at the prompt to create implement cursors for specific types of data.
and populate the new database. SQLiteCursor exposes results from a query on a
n

SQLiteDatabase. SQLiteCursor is not internally


Opening and Closing Android SQLite Database
synchronized, so code using a SQLiteCursor
Connection
from multiple threads should perform its own
· Before performing any database operations like
insert, update, delete records in a table, first open synchronization when using the SQLiteCursor.
· MatrixCursor is an all-rounder, a mutable cursor
the database connection by
callinggetWritableDatabase() method as shown implementation backed by an array of objects that
below : automatically expands internal capacity as needed.
· Some common operations on cursor are :
public DBManager open() throws SQLException { n getCount() returns the number of rows in the
dbHelper = new DatabaseHelper(context); cursor.
database = dbHelper.getWritableDatabase();
n getColumnNames() returns a string array
return this;
holding the names of all of the columns in the
}
result set in the order in which they were listed
The dbHelper is an instance of the subclass of
in the result.
SQLiteOpenHelper.
n getPosition() returns the current position of the
To close a database connection the following method
cursor in the row set.
is invoked.
public void close() {
n Getters are available for specific data types, such
dbHelper.close(); as getString(int column) and getInt(int column).
} n Operations such as moveToFirst() and
moveToNext() move the cursor.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 49 Activity and Multimedia with Databases

n close() releases all resources and makes the cursor completely invalid. Remember to call close to
free resources!

Reading Cursor Data


· Once a cursor has been returned from a database query, an app needs to iterate over the result set
and read the column data from the cursor.
· Internally, the cursor stores the rows of data returned by the query along with a position that points
to the current row of data in the result set.
· When a cursor is returned from a query() method, its position points to the spot before the first row
of data.
· This means that before any rows of data can be read from the cursor, the position must be moved to
point to a valid row of data.

Advantage of SQLite :
1. If you have data related with each other, file will not allow you to relate them. At that time SQLite
will help you.
2. If you want to query your data, store the data in structured manner you will prefer SQLite
3. SQLite has higher performance
4. An SQLite database can also be queried and the data retrieval is much more robust.
5. The study.db and study.db.sqlite packages offer a higher-performance alternative where source
compatibility is not an issue.
6. Android-databases created in Android are visible only to the application that created them
7. There is no file parsing and generating code to write and debug.
8. Content can be accessed and updated using powerful SQL queries, greatly reducing the complexity
of the application code.
9. Extending the file format for new capabilities in later releases is as simple as adding new tables or
new columns to existing tables.
10. Diverse content which might otherwise be stored as a "pile-of-files" can be encapsulated into a
single disk file.
11. The content can be viewed using third-party tools.
12. The application file is portable across all operating systems, 32-bit and 64-bit and big- and
little-endian architectures.
13. The application only has to load as much data as it needs, rather than reading the entire
application file and holding a complete parse in memory. Startup time and memory consumption
are reduced.
14. Small edits only overwrite the parts of the file that change, not the entire file, thus improving
performance and reducing wear on SSD drives.
15. Content is updated continuously and atomically so that there is no work lost in the event of a
power failure or crash.
16. Applications can leverage the full-text search and RTREE capabilities that are built into SQLite.
17. Performance problems can often be resolved using CREATE INDEX rather than redesigning,
rewriting, and retesting application code.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 50 Activity and Multimedia with Databases

18. A federation of programs, perhaps written in different programming languages, can all access the
same application file with no compatibility concerns.
19. Multiple processes can attach to the same application file and can read and write without
interfering with each another.
20. Cross-session undo/redo can be implemented using triggers.
21. In many common cases, loading content from an SQLite database is faster than loading content
out of individual files. See Internal Versus External BLOBs for additional information.
22. Content stored in an SQLite database is more likely to be recoverable decades in the future, long
after all traces of the original application have been lost. Data lives longer than code.

A Simple Android SQLite Example

Step 1 : Create new Android project.

Fig 5.8.1 Android SQLite Database Create Project

Step 2 : Add components in the main activity as shown in the Fig. 5.8.2 below.

Name
Surname
Marks
id

Add Setting New Add

Update Delete

Fig 5.8.2 Android SQLite Database Tutorial. Design Activity

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 51 Activity and Multimedia with Databases

<RelativeLayout xmlns:android="url" study:layout_alignTop="@+id/textView2"


xmlns:tools="url" study:layout_width="match_parent" study:layout_toRightOf="@+id/textView2"
study:layout_height="match_parent" study:layout_toEndOf="@+id/textView2" />
study:paddingLeft="@dimen/act_horizontal_margin" <EditText
study:paddingRight="@dimen/act_horizontal_margin" study:layout_width="match_parent"
study:paddingTop="@dimen/act_vertical_margin" study:layout_height="wrap_content"
study:paddingBottom="@dimen/act_vertical_margin" study:id="@+id/editText_Marks"
tools:context=".MainActivity"> study:layout_below="@+id/editText_surname"
<TextView study:layout_toRightOf="@+id/textView3"
study:layout_width="wrap_content" study:layout_toEndOf="@+id/textView3" />
study:layout_height="wrap_content" <Button
study:layout_width="wrap_content"
study:textAppearance="?study:attr/textAppearanceLarge" study:layout_height="wrap_content"
study:text="Name" study:text="Add Data"
study:id="@+id/textView" study:id="@+id/button_add"
study:layout_alignParentTop="true" study:layout_below="@+id/editText_Marks"
study:layout_alignParentLeft="true" study:layout_alignParentLeft="true"
study:layout_alignParentStart="true" /> study:layout_alignParentStart="true"
<TextView study:layout_marginTop="76dp" />
study:layout_width="wrap_content" <Button
study:layout_height="wrap_content" study:layout_width="wrap_content"
study:layout_height="wrap_content"
study:textAppearance="?study:attr/textAppearanceLarge" study:text="View All"
study:text="Surname" study:id="@+id/button_viewAll"
study:id="@+id/textView2" study:layout_above="@+id/button_update"
study:layout_below="@+id/editText_name" study:layout_centerHorizontal="true" />
study:layout_alignParentLeft="true" <Button
study:layout_alignParentStart="true" /> study:layout_width="wrap_content"
<TextView study:layout_height="wrap_content"
study:layout_width="wrap_content" study:text="Update"
study:layout_height="wrap_content" study:id="@+id/button_update"
study:layout_below="@+id/button_add"
study:textAppearance="?study:attr/textAppearanceLarge" study:layout_alignParentLeft="true"
study:text="Marks" study:layout_alignParentStart="true" />
study:id="@+id/textView3" <Button
study:layout_below="@+id/editText_surname" study:layout_width="wrap_content"
study:layout_alignParentLeft="true" study:layout_height="wrap_content"
study:layout_alignParentStart="true" /> study:text="Delete"
<EditText study:id="@+id/button_delete"
study:layout_width="match_parent" study:layout_centerVertical="true"
study:layout_height="wrap_content" study:layout_below="@+id/button_viewAll"
study:id="@+id/editText_name" study:layout_alignLeft="@+id/button_viewAll"
study:layout_alignTop="@+id/textView" study:layout_alignStart="@+id/button_viewAll" />
study:layout_toRightOf="@+id/textView" <TextView
study:layout_toEndOf="@+id/textView" /> study:layout_width="wrap_content"
<EditText study:layout_height="wrap_content"
study:layout_width="match_parent"
study:layout_height="wrap_content" study:textAppearance="?study:attr/textAppearanceLarge"
study:id="@+id/editText_surname" study:text="id"

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 52 Activity and Multimedia with Databases

study:id="@+id/textView_id"
study:layout_below="@+id/editText_Marks"
study:layout_alignParentLeft="true"
study:layout_alignParentStart="true" />
<EditText
study:layout_width="match_parent"
study:layout_height="wrap_content"
study:id="@+id/editText_id"
study:layout_alignTop="@+id/textView_id"
study:layout_toRightOf="@+id/textView3"
study:layout_toEndOf="@+id/textView3" />
</RelativeLayout>

Step 3 : Now create a new Java class called DatabaseHelper.java.

Fig 5.8.3 Android SQLite Database Tutorial. DatabaseHelper

Add the following code in this class to DatabaseHelper.java


package my.example.programmingknowledge.sqliteapp;
import study.content.ContentValues;
import study.content.Context;
import study.db.Cursor;
import study.db.sqlite.SQLiteDatabase;
import study.db.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "SURNAME";
public static final String COL_4 = "MARKS";

public DatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, 1);
}
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 53 Activity and Multimedia with Databases

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME
TEXT,SURNAME TEXT,MARKS INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean updateData(String id,String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
}
MainActivity.java
package my.example.programmingknowledge.sqliteapp;
import android.app.AlertDialog;
import study.db.Cursor;
import study.support.v7.app.ActionBarActivity;
import study.os.Bundle;
import study.view.Menu;

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 54 Activity and Multimedia with Databases

import study.view.MenuItem;
import study.view.View;
import study.widget.Button;
import study.widget.EditText;
import study.widget.Toast;

public class MainActivity extends ActionBarActivity {


DatabaseHelper myDb;
EditText editName,editSurname,editMarks ,editTextId;
Button btnAddData;
Button btnviewAll;
Button btnDelete;
Button btnviewUpdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editSurname = (EditText)findViewById(R.id.editText_surname);
editMarks = (EditText)findViewById(R.id.editText_Marks);
editTextId = (EditText)findViewById(R.id.editText_id);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
btnviewUpdate= (Button)findViewById(R.id.button_update);
btnDelete= (Button)findViewById(R.id.button_delete);
AddData();
viewAll();
UpdateData();
DeleteData();
}
public void DeleteData() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(editTextId.getText().toString());
if(deletedRows > 0)
Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Deleted",Toast.LENGTH_LONG).show();
}
}
);
}
public void UpdateData() {
btnviewUpdate.setOnClickListener(
new View.OnClickListener() {
@Override

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 55 Activity and Multimedia with Databases

public void onClick(View v) {


boolean isUpdate = myDb.updateData(editTextId.getText().toString(),
editName.getText().toString(),
editSurname.getText().toString(),editMarks.getText().toString());
if(isUpdate == true)
Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();
}
}
);
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editName.getText().toString(),
editSurname.getText().toString(),
editMarks.getText().toString() );
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
} }
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Id :"+ res.getString(0)+"\n");
buffer.append("Name :"+ res.getString(1)+"\n");
buffer.append("Surname :"+ res.getString(2)+"\n");
buffer.append("Marks :"+ res.getString(3)+"\n\n");
}
// Show all data
showMessage("Data",buffer.toString());
} }
);

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 56 Activity and Multimedia with Databases

}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}

Output

Name Tom Data


Surname Beme
id : 1
Name Tom Marks 78 Name : Mark
Surname Beme id 5 Surname : Benson
Marks 78 Marks : 89
ADD DATA VIEW ALL
id 5 id : 4
Name : John
ADD DATA VIEW ALL UPDATE DELETE Surname : Dep
Marks : 80
UPDATE DELETE
id : 5
Name : Tom
Data Inserted
Surname : Beme
Marks : 78

Fig 5.8.4 Add Data Fig. 5.8.5 Data Successfully added to Fig. 5.8.6 View Data
sqlite database

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 57 Activity and Multimedia with Databases

5.8.4 Transactions · If endTransaction() is called without a call to


· Insert, update, and delete operations manipulate setTransactionSuccessful(), the transaction will be
tables and rows in a database. rolled back, undoing all of the operations in the
transaction.
· While each operation is atomic (will either succeed
or fail on its own), it is sometimes necessary to · Because the call to setTransactionSuccessful() affects
group a set of operations together and have the set what happens during theendTransaction() call, it is
of operations be atomic. considered a best practice to limit the number of
non-database operations between a call to
· There are times when a set of related operations
setTransactionSuccessful() and endTransaction().
should be allowed to manipulate the database only
if all operations succeed to maintain database · Additionally, do not perform any additional
integrity. database manipulation operations between the call
tosetTransactionSuccessful() and endTransaction().
· For these cases, a database transaction is usually
used to ensure that the set of operations is atomic. · Once the call tosetTransactionSuccessful() is made,
the transaction is marked as clean and is committed
· In Android, the SQLiteDatabase class contains the
in the call to endTransaction() even if errors have
following methods to support transaction
occurred after the call tosetTransactionSuccessful().
processing :
n void beginTransaction(): Begins a transaction Transaction Example
SQLiteDatabase db = getDatabase();
n void setTransactionSuccessful(): Indicates that
db.beginTransaction();
the transaction should be committed
try {
n void endTransaction() : Ends the transaction // insert/update/delete
causing a commit if set - Transaction has been // insert/update/delete
called Successfully to End. // insert/update/delete
db.setTransactionSuccessful();
Using a Transaction } finally {
·A transaction is started with the db.endTransaction(); }
SQLiteDatabase.beginTransaction() method. · Database operations that happen in a transaction as
· Once a transaction is started, calls to any of the well as the call to setTransaction() should take place
data manipulation method calls (insert(), update(), in a try block with the call to endTransaction()
delete()) may be made. happening in a finally block.
· Once all of the manipulation calls have been made, · This ensures that the transaction will be ended even
the transaction is ended with if an unhandled exception is thrown while
SQLiteDatabase.endTransaction(). modifying the database.
· To mark the transaction as successful, allowing all
the operations to be committed,
SQLiteDatabase.setTransactionSuccessful()must be qqq
called before the call to
SQLiteDatabase.endTransaction() is made.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 5 - 58 Activity and Multimedia with Databases

Notes

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - VI

6
6.1 SMS Telephony
Security and Application Deployment

n This is a good choice for sending messages from


· The telephony system is a software framework to
your app without having to use another
provide mobile phones with telephony installed app.
functionalities, such as voice call, Video call, SMS, n Your app must ask the user for permission
MMS, data service, network management and so on. before sending the SMS message, if the user
· The android telephony class provides information hasn't already granted permission.
about the telephony services such as subscriber id, n The user stays in your app during and after
sim serial number, phone network type etc. sending the message.

6.1.1 Sending and Receiving SMS Messages nYou can manage SMS operations such as
dividing a message into fragments, sending a
Android smartphones can send and receive messages
multipart message, get carrier-dependent
to or from any other phone that supports Short
configuration values, and so on.
Message Service (SMS).
To receive SMS messages, use the onReceive()
You have two choices for sending SMS messages : method of the BroadcastReceiver class.
· Use an implicit Intent to launch a messaging app
with the ACTION_SENDTO intent action. 6.2 Location Based Service
n This is the simplest choice for sending messages.
Developing applications for mobile devices gives us a
The user can add a picture or other attachment lot more opportunities for context based information
in the messaging app, if the messaging app than a traditional web application.
supports adding attachments.
One of the inputs for context sensitive information is
n Your app doesn't need code to request
the users current location.
permission from the user.
n If the user has multiple SMS messaging apps 6.2.1 Location API's
installed on the Android phone, the App This was not ideal since as a developer of an
chooser will appear with a list of these apps, application, you probably are not concerned about
and the user can choose which one to use. the implementation details of obtaining users location.
(Android smartphones will have at least one, Fortunately Google's Location API's provide a much
such as Messenger.) better way for working with location data.
n The user can change the message in the
The Location API's provide the following
messaging app before sending it.
functionality :
n The user navigates back to your app using the · Fused location provider which abstracts away the
Back button. underlying location providers.
· Send the SMS message using the sendTextMessage()
· Geofencing. Lets your application setup geographic
method or other methods of the SmsManager class.
boundaries around specific locations and then

(6 - 1)® - An up thrust for knowledge


TECHNICAL PUBLICATIONS
Mobile Application Development 6-2 Security and Application Deployment

receive notifications when the user enters or leaves Any app that wants to behave as the user's default
those areas. SMS app must handle the following intents:
· Activity recognition. Is the user walking or in a car. · In a broadcast receiver, include an intent filter. The
Android System gives the opportunity to determine broadcast receiver must also require the
the current geographical location and to build BROADCAST SMS permission. This allows your
location-aware applications, without focusing on the app to directly receive incoming SMS messages.
details of the underlying location technology. · In a broadcast receiver, include an intent filter for
the broadcast receiver must also require the
To obtain the user location, we can use one of :
BROADCAST_WAP_PUSH permission. This allows
· GPS Provider
your app to directly receive incoming MMS
· Android's Network Location Provider (availability messages.
of cell tower and WiFi access points)
· In your activity that delivers new messages, include
Every provider has it's cons and pros and can be an intent filter for SENDTO with schemas, sms:,
used depending on the circumstances at each smsto:, mms:, and mmsto:. This allows your app to
situation. receive intents from other apps that want to deliver
For example GPS, is exact and more appropriate for a message.
outdoors, but it consumes a lot of battery power. On · In a service, include an intent filter for Telephony
the other hand, network provider works for indoors Manager with schemas, sms:, smsto:, mms:, and
as well for outdoors and has a lower battery mmsto:.This service must also requirethe
consumption and a faster response. SEND_RESPOND_VIA_MESSAGE permission.
Location Based Services are provided by Android · This allows users to respond to incoming phone
through its location framework. calls with an immediate text message using your
app.
The framework provides a location API which
Other apps that are not selected as the default SMS
consists of certain classes and interface.
app can only read the SMS Provider, but may also be
These classes and interface are the key components notified when a new SMS arrives by listening for the
which allow us to develop Location Based RECEIVED_ACTION broadcast.
Application in Android.
6.2.3 Getting the Maps API Key
6.2.1.1 Classes and Interfaces of Location Based Services
LocationManager - This class helps to get access to 6.2.3.1 What is a Google Maps API Key ?
the location service of the system. ·A Google Maps API key is a personal code
provided by Google to access Google Maps on this
LocationListener - This interface acts as the listener
site.
which receives notification from the location manager
when the location changes or the location provider is · Your API key provides you with a free quota of

disabled or enabled. Google Map queries.


· Your Google account will be automatically billed for
Location - This is the class which represents the
any usage that exceeds your quota.
geographic location returned at a particular time.
6.2.3.2 How to get a Google Maps API Key ?
6.2.2 Creating the Project
· Getting an API key is not too complicated and takes
6.2.2.1 Creating an SMS App a few minutes. You will need to create a billing
Only the default SMS app is able to write to the SMS account or use an existing one.
Provider and only the default SMS app receives the · To use the Maps SDK for Android you must have
Telephony. Sms broadcast when the user receives an an API key.
SMS.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-3 Security and Application Deployment

· The API key is a unique identifier that is used to Step 4 :


authenticate requests associated with your project In this open Enable APIS AND SERICES.
for usage and billing purposes.
· Get the API key
· You must have at least one API key associated with
your project.

Steps for Getting the Google Maps API Key :


· An API key is needed to access the Google Maps
servers.
· This key is free and you can use it with any of your
Fig 6.2.3 Enable APIS AND SERICES
applications.
Step 5 :
· If you haven't created project, you can follow the
below steps to get started : Now open Google Map Android API.

Step 1 :
Open Google developer console and signin with your
gmail account :
https://console.developers.google.exm/project

Step 2 :
Now create new project. You can create new project
by clicking on the Create Project button and give Fig 6.2.4 Google Map Android API
name to your project.
Step 6 :
Now enable the Google Maps Android API.

Fig. 6.2.1 Creating a project


Step 3 :
Fig. 6.2.5 Enable google map
Now click on APIs & Services and open Dashboard
Step 7 :
from it.
Now go to Credentials

Fig 6.2.6 Credentials

Step 8 :
Fig 6.2.2 Opening a dashboard Here click on Create credentials and choose API key

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-4 Security and Application Deployment

6.2.4 Displaying the Map


· Android allows us to integrate google maps in our
application.
· You can show any location on the map, or can
show different routes on the map etc.
· You can also customize the map according to your
choices.
· In order to implement, you need to follow the
pre-steps given below:

1. Downloading Google Play Services :


Fig. 6.2.7 Create credentials You need to download Google Play Services from
SDK Manager.
Step 9 :
Now API your API key will be generated. Copy it Goto Window->SDK Manager->Extras->check Google
and save it somewhere as we will need it when Play Services.
implementing Google Map in our Android project.
2. Importing Google Play Services into Eclipse :
After downloading play services, we need to import
it to Eclipse which will be used as a library for our
maps project.

1. In Eclipse File->New->Other-> Android->


Android Project from existing code
2. Click on Browse and select Google Play Services
project from your android SDK folder. You can
locate play services library from
android-sdk-windows\extras\google\google_play_ser
Fig. 6.2.8 API key creation
vices\libproject\google-play-services_lib

Fig 6.2.9 Downloading Google Play Services

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-5 Security and Application Deployment

3. Importantly, while importing, check Copy projects into workspace option as shown in the below
image.

Fig. 6.2.10 Importing project


3. Getting Google Map API Key :
We need to generate SHA-1 fingerprint using java keytool(debug mode).
Open command prompt and execute the following command to generate finger print.
Ex :
On Windows
Keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore"
-alias androiddebugkey -storepass android -keypass android
On Linux or Mac Os :
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass
android
In the output you can see SHA 1 finger print.

Fig. 6.2.11 Fingerprints

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-6 Security and Application Deployment

When your application enters the production mode


from the debug mode, you need a signed apk to
upload in the playstore and SHA-1 finger print
(which is generated during singning an apk) for
getting signed Google Map Signed API key.
· Open Google API Console. Click on create project,
accept the terms and conditions
· Click on API project->create project->enter project
name->click on create
Select API's on left->enable Google Map Android API Fig. 6.2.12 Create project

Fig 6.2.13 Enable Google Map Android API


Click on credentials on left->click on create new key->select android key->
Enter SHA-1 finger print and package of your project as per the instructions given->click on create and
you are done.

Fig. 6.2.14 Creating a key

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-7 Security and Application Deployment

Fig 6.2.15 Create and configure application


4. Create a New project : 6.2.4.1 Google Map - Layout File
Create a new project, right click on Android allows us to integrate Google Maps in our
project->properties->Android->add->click on google application.
play services->apply->ok
For this Google provides us a library via Google Play
Add the Map Key in the manifest file. Open Services for using maps.
AndroidManifest.xml file and add the following code
In order to use the Google Maps API, you must
before the tag. Replace the android value with your
register your application on the Google Developer
map key which you got from the google console.
Console and enable the API.
<!-- Goolge Maps API Key -->

<meta-data

study:name="my.ex.maps.API_KEY"

study:value="Your_API_Key" />

Google maps need the following permissions and


features.

Add the following permissions to your manifest.

ACCESS_NETWORK_STATE - To check the network


state, whether data can be downloaded or not.
Fig. 6.2.16 Access permission
INTERNET - To check internet connection status.
Now you have to add the map fragment into xml
WRITE_EXTERNAL_STORAGE - To write to external layout file. Its syntax is given below ?
storage as google maps store map data in external <fragment
storage. study:id="@+id/map"
ACCESS_COARSE_LOCATION - To determine user's study:name="my.ex.gms.maps.MapFragment"
location using WiFi and mobile cell data. study:layout_width="match_prnt"
study:layout_height="match_prnt"/>
ACCESS_FINE_LOCATION - To determine user's
location using GPS. 6.2.4.2 Google Map - Android Manifest File

OpenGL ES V2 - Required for Google Maps V2. The next thing you need to do is to add some
permissions along with the Google Map API. Its
Add the following features to your manifest. syntax is given below :
<!-- Required OpenGL ES 2.0. for Maps V2 --> <!--Permissions-->
<uses-permission
<uses-feature
study:name="android.permission.ACCESS_NETWORK_STA
study:glEsVersion="0x00020000" TE" />
<uses-permission
study:required="true" />
study:name="android.permission.INTERNET" />
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-8 Security and Application Deployment

<uses-permission 1. hide() : This method is used to hide the Zoom


study:name="my.ex.providers.gsf.permission. Controls from the screen. In some cases we need to
READ_GSERVICES" /> hide the Zoom Controls from the screen so that we
<uses-permission use this function.
study:name="android.permission.WRITE_EXTERNAL_STOR
AGE" />
2. show() : This method is used to show the Zoom
<!--Google MAP API key--> Controls which we hide from the screen by using
<meta-data hide method.
study:name="my.ex.maps.API_KEY"
6.2.6 Navigating to Specific Location
study:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVy
Q0" />
6.2.6.1 Android Google Map Displaying Current Location
6.2.4.3 Customizing Google Map To display the user current location we need to
You can easily customize google map from its default implements some interfaces and there callbacks
view , and change it according to your demand. methods.

6.2.4.4 Changing Map Type Get the Current Location


You can also change the type of the MAP. There are To get the current location, create a location client
four different types of map and each give a different which is Location Client object, connect it to Location
view of the map. These types are Services using connect() method, and then call its
Normal,Hybrid,Satellite and terrain. You can use getLastLocation() method.
them as below
This method returns the most recent location in the
gmap.setMapType(Gmap.MAP_TYPE_NORMAL); form of Location object that contains latitude and
gmap.setMapType(Gmap.MAP_TYPE_HYBRID); longitude coordinates and other information as
gmap.setMapType(Gmap.MAP_TYPE_SATELLITE);
explained above. To have location based functionality
gmap.setMapType(Gmap.MAP_TYPE_TERRAIN);
in your activity, you will have to implement two
interfaces -
6.2.5 Displaying the Zoom Control
· GooglePlayServicesClient.ConnectionCallbacks
6.2.5.1 Enable/Disable Zoom · GooglePlayServicesClient.OnConnectionFailedListener
You can also enable or disable the zoom gestures in These interfaces provide following important callback
the map by calling the set ZoomControlsEnabled methods, which you need to implement in your
(boolean) method. Its syntax is given below ? activity class -
gmap.getUiSettings().setZoomGesturesEnabled(true);
Apart from these customization, there are other Sr. No. Callback Methods and Description

methods available in the Gmap class , that helps you 1. abstract void onConnected(Bundle
more customize the map. connectionHint)
This callback method is called when location
In Android, Zoom Controls class display simple set service is connected to the location client
of controls that is used for zooming and provides successfully. You will use connect () method to
connect to the location client.
callback to register for events. Zoom Controls has
two buttons Zoom In and Zoom Out which are used 2. abstract void onDisconnected()
to control the zooming functionality. This callback method is called when the client
is disconnected. You will use disconnect
6.2.5.2 Important Methods of Zoom Controls () method to disconnect from the location client.

Now let's discuss some common methods which are 3. abstract void
used to configure Zoom Controls in our application. onConnectionFailed(ConnectionResult result)
This callback method is called when there was
an error connecting the client to the service.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6-9 Security and Application Deployment

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.

6.2.6.2 Callback Methods in Google Map


1. OnMapRreadyCallback : This callback interface invokes when it instance is set on MapFragment
object. The onMapReady(Gmap) method of OnMapReadyCallback interface is called when the map
is ready to used. In the onMapReady(Gmap) method we can add markers, listeners and other
attributes.
2. LocationListener : This interface is used to receive notification when the device location has
changed. The abstract method of LocationListener onLocationChanged(Location) is called when the
location has changed.
3. GoogleApiClient.ConnectionCallbacks : This interface provide callbacks methods
onConnected(Bundle) and onConnectionSuspended(int) which are called when the device is to
connected and disconnected.
4. GoogleApiClient.OnConnectionFailedListener : This interface provide callbacks method
onConnectionFailed(ConnectionResult) which is called when there was an error in connecting the
device to the service.
The setMyLocationEnabled() method of Gmap is used to enable location layer, which allows device to
interact with current location.

6.2.7 Adding Markers


You can place a maker with some text over it displaying your location on the map. It can be done by
via addMarker() method. Its syntax is given below -
final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = gmap.addMarker(new MarkerOptions()
.position(TutorialsPoint).title("TutorialsPoint"));

6.2.8 Getting Location, Getting Location data, Monitoring Location

Example To Access User Current Location In Android Studio :


In the below Google Map example will show user
current location in Map. Also example different
map types, methods and lots more details required
while implementing Map in Android.

Step 1 : Create a New Android Project and name


it Gmaps.

Step 2 : Now select Google Maps Activity and


then click Next and finish.

Step 3 : Now open google_maps_api.xml (debug)


in values folder
Fig 6.2.17 Access permission

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 10 Security and Application Deployment

Fig 6.2.18 Google Maps Activity and then click Next and finish

Fig 6.2.19 Put google map API key

Step 4 : Here enter your Google Maps API key in Step 7 : Now define internet and location
place of YOUR_KEY_HERE. permissions in Android Manifest
Step 5 : Now open build.gradle and add compile Step 8 : Now we will code MapsActivity.java file
'my.ex.gms:play-services:8.4.0' in dependencies for inserting callbacks in Google Maps
Step 6 : Now open activity_maps.xml and add a
6.2.9 Geocoding and Reverse Geocoding
fragment code in it
· Android Geocoder class is used for Geocoding as
Here add a fragment element to the activity's layout well as Reverse Geocoding. Geocoding refers to
file to define a Fragment object. In this element, set transforming street address or any address into
the study:name attribute to latitude and longitude.
"my.ex.gms.maps.MapFragment". · Reverse Geocoding refers to transforming latitude
and longitude into its corresponding street address.
This automatically attaches a MapFragment to the
activity. · Geocoding is the process of transforming a
description of a location-such as a pair of
coordinates, an address, or a name of a place-to a
location on the earth's surface.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 11 Security and Application Deployment

· You can geocode by entering one location description at a time or by providing many of them at once
in a table.
· Android Geocoder class is used for Geocoding as well as Reverse Geocoding.
· Reverse geocoding is the process of back (reverse) coding of a point location (latitude, longitude) to a
readable address or place name.
· Reverse Geocoding refers to transforming latitude and longitude into its corresponding street address.
· The process of turning coordinates into a String address is called reverse geocoding.
· Instead of supplying the builder with a String address you'd pass in coordinates instead.
· Handling the response is like forward geocoding.
· While the geocoder gives one coordinate, the response will often give you multiple valid ways to
describe the specific location.
· For example, one might be the street name while another result will be the country. The ordering of
the list usually goes from most relevant to least.
Geocoding request :
Before making a geocoding request, you must build the MapboxGeocoding object by passing in two
required parameters; a valid Mapbox access token and a location query (typically an address or
description). Many other parameters are available to help bias and manipulate the response that you
receive.
MapboxGeocoding mapboxGeocoding = MapboxGeocoding.builder()
.accessToken(MAPBOX_ACCESS_TOKEN)
.query("1600 Pennsylvania Ave NW")
.build();
Geocoding response
Once you have built your MapboxGeocoding object with all the parameters that you'd like to use in
the request, you'll need to asynchronously send the request using enqueueCall(). Once the request
receives a response, it will tell the callback where you can handle the response appropriately.
mapboxGeocoding.enqueueCall(new Callback<GeocodingResponse>() {
@Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
List<CarmenFeature> results = response.body().features();
if (results.size() > 0) {
// Log the first results Point.
Point firstResultPoint = results.get(0).center();
Log.d(TAG, "onResponse: " + firstResultPoint.toString());
} else {

// No result for your request were found.


Log.d(TAG, "onResponse: No result found");
}
}
@Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
throwable.printStackTrace();
}
});
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 12 Security and Application Deployment

6.3 Android Security Model well as certain system features (such as camera and
internet).
The security model adopted by Android is Identity
Based. Answer : The security model adopted by · Depending on the feature, the system might grant
Android is the Linux OS based, where the the permission automatically or might prompt the
applications need to take permission from the user user to approve the request.
before using any hardware component of the · A central design point of the Android security
androiddevice. architecture is that no app, by default, has
permission to perform any operations that would
Android's Security Model :
adversely impact other apps, the operating system,
· Like the rest of the system, Android's security
or the user.
model also takes advantage of the security features
offered by the Linux kernel. · This includes reading or writing the user's private
data (such as contacts or emails), reading or writing
· Linux is a multiuser operating system and the
another app's files, performing network access,
kernel can isolate user resources from one another,
keeping the device awake, and so on.
just as it isolates processes.
· In a Linux system, one user cannot access another 6.3.1.1 Define a Custom App Permission
user's files (unless explicitly granted permission) · By defining custom permissions, an app can share
and each process runs with the identity (user and its resources and capabilities with other apps.
group ID, usually referred to as UID and GID) of Android is a privilege-separated operating system,
the user that started it, unless the set-user-ID or in which each app runs with a distinct system
set-group-ID (SUID and SGID) bits are set on the identity (Linux user ID and group ID). Parts of the
corresponding executable file. system are also separated into distinct identities.
· Android takes advantage of this user isolation, but · Linux thereby isolates apps from each other and
treats users differently than a traditional Linux from the system.
system (desktop or server) does.
· Apps can expose their functionality to other apps
· In a traditional system, a UID is given either to a by defining permissions which those other apps can
physical user that can log into the system and request.
execute commands via the shell, or to a system
· They can also define permissions which are
service (daemon) that executes in the background
automatically made available to any other apps
(because system daemons are often accessible over
which are signed with the same certificate.
the network, running each daemon with a dedicated
UID can limit the damage if one is compromised). 6.3.1.2 App Signing
· Android was originally designed for smartphones, · All APKs must be signed with a certificate whose
and because mobile phones are personal devices, private key is held by their developer.
there was no need to register different physical · This certificate identifies the author of the app.
users with the system.
· The certificate does not need to be signed by a
· The physical user is implicit, and UIDs are used to certificate authority; it is perfectly allowable, and
distinguish applications instead. typical, for Android apps to use self-signed
· Thisforms the basis of Android's application certificates.
sandboxing. · The purpose of certificates in Android is to
distinguish app authors.
6.3.1 Declaring and using Permissions
· This allows the system to grant or deny apps access
· The purpose of a permission is to protect the
to signature-level permissions and to grant or deny
privacy of an Android user.
an app's request to be given the same Linux
· Android apps must request permission to access identity as another app.
sensitive user data (such as contacts and SMS), as
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 13 Security and Application Deployment

6.3.1.3 User IDs and File Access · You must do this if the apps are not all signed with
· At install time, Android gives each package a the same certificate.
distinct Linux user ID. · Even if the apps are all signed with the same
· The identity remains constant for the duration of certificate, it's a best practice to define each
the package's life on that device. permission once only.
· On a different device, the same package may have a · If the functionality is only available to apps signed
different UID; what matters is that each package with the same signature as the providing app, you
has a distinct UID on a given device. may be able to avoid defining custom permissions
· Because security enforcement happens at the by using signature checks.
process level, the code of any two packages cannot · When one of your apps makes a request of another
normally run in the same process, since they need of your apps, the second app can verify that both
to run as different Linux users. apps are signed with the same certificate before
· Any data stored by an app will be assigned that
complying with the request.
app's user ID, and not normally accessible to other
packages. 6.4 Application Deployment

6.3.1.4 Create a Permission Group 6.4.1 Creating Small Application


· It help the system describe permissions to the user.
Steps to create small application using android
In most cases you will want to set this to a
standard system group, but you can also define Step 1 : A great imagination leads to a great app. ...
your own group with <permission-group>. Step 2 : Identify. ...
· The <permission-group> element defines a label for
Step 3 : Design your app. ...
a set of permissions-both those declared in the
manifest with <permission> elements and those Step 4 : Identify approach to develop the app -
declared elsewhere. native, web or hybrid. ...
· This affects only how the permissions are grouped Step 5 : Develop a prototype. ...
when presented to the user.
Step 6 : Integrate an appropriate analytics tool. ...
· The <permission-group> element does not specify
the permissions that belong to the group, but it Step 7 : Identify beta-testers. ...
gives the group a name. Step 8 : Release / deploy the app.
· You can place permission in the group by assigning
the group name to the <permission> element's 6.4.2 Signing of Application
permission Group attribute. · Android requires that all apps be digitally signed
· The <permission-tree> element declares a namespace with a certificate before they can be installed.
for a group of permissions that are defined in code. · Android uses this certificate to identify the author
of an app, and the certificate does not need to be
6.3.2 Using Custom Permission signed by a certificate authority.
· Apps can define their own custom permissions and · Android apps often use self-signed certificates.
request custom permissions from other apps by
· The app developer holds the certificate's private
defining <uses-permission> elements.
key.
· However, you should carefully assess whether it is
necessary for your app to do so. 6.4.2.1 Signing in Debug Mode
· If you are designing a suite of apps that expose · In debug mode, you sign your app with a debug
functionality to one another, try to design the apps certificate generated by the Android SDK tools.
so that each permission is defined only once.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 14 Security and Application Deployment

· This certificate has a private key with a known Once you create the profile, it will be automatically
password, so you can run and debug your app linked to your developer account.
without typing the password every time you make
a change to your project. Step 3 : Create an App
· Android Studio signs your app in debug mode
Now that you have set up your Play Console, you
automatically when you run or debug your project can finally add your app. Here's how to do that :
from the IDE. 1. Navigate to the 'All applications' tab in the menu
· You can run and debug an app signed in debug 2. Click on 'Create Application'
mode on the emulator and on devices connected to
3. Select your app's default language from the
your development manchine through USB, but you
drop-down menu
cannot distribute an app signed in debug mode.
4. Type in a title for your app
· By default, the debug configuration uses a debug
keystore, with a known password and a default key 5. Click on "Create"
with a known password. The title of your app will show on Google Play after
you've published. Don't worry too much about it at
6.4.2.2 Signing in Release Mode
this stage; you can always change the name later.
In release mode, you sign your app with your own
After you've created your app, you'll be taken to the
certificate :
store entry page. Here, you will need to fill out all
1. Create a keystore. A keystore is a binary file that the details for your app's store listing.
contains a set of private keys. You must keep
your keystore in a safe and secure place. Step 4 : Prepare Store Listing
2. Create a private key. A private key represents · Before you can publish your app, you need to
the entity to be identified with the app, such as a prepare its store listing.
person or a company. · These are all the details that will show up to
3. Add the signing configuration to the build file customers on your app's listing on Google Play.
for the app module. Note : You don't necessarily have to complete this
step before moving on to the next one. You can
6.4.3 Deploying App on Google Play Store, always save a draft and revisit it later when you're
Become a Publisher, Developer Console ready to publish.
Step 1 : Create a Developer Account
Step 5 : Upload APK to an App Release
· Before you can publish any app on Google Play,
· Now that you have prepared the ground to finally
you need to create a Developer Account.
upload your app, it's time to dig out your APK file.
· You can easily sign up for one using your existing
· The Android Package Kit (or APK, for short) is the
Google Account.
file format used by the Android operating system to
Step 2 : Plan to Sell ? Link Your Merchant Account distribute and install apps.
If you want to publish a paid app or plan to sell · Simply put, your APK file contains all the elements
in-app purchases, you need to create a payments needed for your app to actually work on a device.
center profile, i.e. a merchant account. Here's how
· Google offers you multiple ways to upload and
you can do that :
release your APK. Before you upload the file,
1. Sign in to your Play Console however, you need to create an app release.
2. Click on Download Reports - Financial · To create a release, select the app you created in

3. Select 'Set up a merchant account now' Step 3.


· Then, from the menu on the left side, navigate to
4. Fill out your business information
'Release management' -> 'App releases.'
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 15 Security and Application Deployment

· Here, you need to select the type of release you Step 7 : Set Up Pricing and Distribution
want to upload your first app version to. · Before you can fill out the details required in this
step, you need to determine your app's
· You can choose between an internal test, a closed
monetization strategy.
test, an open test, and a production release.
· Once you know how your app is going to make
· The first three releases allow you to test out your
money, you can go ahead and set up your app as
app among a select group of users before you make
free or paid.
it go live for everyone to access.
· However, if you create a production release, your Step 8 : Rollout Release to Publish Your App
uploaded app version will become accessible to · You're almost done. The final step involves
everyone in the countries you choose to distribute it reviewing and rolling out your release after making
in. sure you've taken care of everything else.
· Once you've picked an option, click on 'Create · Before you review and rollout your release, make
release.' sure the store listing, content rating, and pricing
· Next, follow the on-screen instructions to add your and distribution sections of your app each have a
APK files, and name and describe your release. green check mark next to them.
· Once you're sure you've filled out those details,
Step 6 : Provide an Appropriate Content Rating
select your app and navigate to 'Release
· If you don't assign a rating to your app, it will be
management' - 'App releases.' Press 'Edit release'
listed as 'Unrated'. Apps that are 'Unrated' may get
next to your desired release, and review it.
removed from Google Play.
· Next, click on 'Review' to be taken to the 'Review
· To rate your app, you need to fill out a content
and rollout release' screen. Here, you can see if
rating questionnaire. You can access it when you
there are any issues or warnings you might have
select your app in the Play Console, and navigate to
missed out on.
'Store presence' - 'Content rating' on the left menu.
· Finally, select 'Confirm rollout.' This will also
· Make sure you enter accurate information.
publish your app to all users in your target
Misrepresentation of your app's content can lead to
countries on Google Play.
suspension or removal from the Play Store.
· An appropriate content rating will also help you get
to the right audience, which will eventually qqq
improve your engagement rates.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development 6 - 16 Security and Application Deployment

Notes

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
SOLVED SAMPLE TEST PAPER - I
Mobile Application Development
T.Y. Diploma Sem - VI
Computer Engg. Program Group (CO/CM/IF/CW)

Time : 1 Hour] [Total Marks : 20

Instructions :

1) All questions are compulsory.

2) Illustrate your answers with neat sketches wherever necessary.

3) Figures to the right indicate full marks.

4) Assume suitable data, if necessary.

5) Preferably write the answers in sequential order.


Q.1 Attempt any FOUR. [8]

a) State difference between Windows operating system and Android operating system. (Refer section 1.1)
b) List various IDEs that can be used to execute Android operating system. (Refer section 1.3)
c) List different attributes which can be used with any layout managers. (Refer section 3.3.1)
d) List features of Android Operating System. (Refer section 1.2)
e) State the steps for creating the Virtual device. (Refer section 2.3)
Q.2 Attempt any THREE. [12]

a) Differentiate between JVM and DVM. (Refer section 2.5)


b) Write a program to place Name, Age and mobile number centrally on the display screen using Absolute layout.
(Refer section 3.3.2)
c) Explore the Steps to install and configure Android Studio and SDK. (Refer section 2.6.3)
d) Write a program to display 10 students basic information in a table form using Table layout.
(Refer section 3.3.4)

qqq

(S - 1)
Mobile Application Development S-2 Solved Sample Papers

SOLVED SAMPLE TEST PAPER - II


Mobile Application Development
T.Y. Diploma Sem - VI
Computer Engg. Program Group (CO/CM/IF/CW)

Time : 1 Hour] [Total Marks : 20

Instructions :

1) All questions are compulsory.

2) Illustrate your answers with neat sketches wherever necessary.

3) Figures to the right indicate full marks.

4) Assume suitable data, if necessary.

5) Preferably write the answers in sequential order.


Q.1 Attempt any FOUR. [8]

a) Enlist different attributes for Edit Text. (Refer section 4.1.2.1)


b) Enlist different buttons. (Refer section 4.1.3)
c) Enlist different uses of Intent (Refer section 5.1.1)
d) Draw neat sketch for Android System Architecture. (Refer section 5.5)
e) Describe the term SMS telephony. (Refer section 6.1)
f) Write a short note on geocoding. (Refer section 6.2.8)
Q.2 Attempt any THREE. [12]

a) Explain grid view. Enlist different methods of grid view. (Refer section 4.2.1)
b) Describe in detail Time & Date Picker. (Refer section 4.3)
c) Explain activity life cycle in detail (Refer section 5.2)
d) Write a short note on SQLite database. Enlist their advantages. (Refer section 5.8)
e) Explain the term Android security model (Refer section 6.3)
f) Explain process of application deployment in detail (Refer section 6.4)

qqq

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
SOLVED SAMPLE QUESTION PAPER
Mobile Application Development
T.Y. Diploma Sem - VI
Computer Engg. Program Group (CO/CM/IF/CW)

Time : 3 Hours] [Total Marks : 70

Instructions :

1) All questions are compulsory.

2) Illustrate your answers with neat sketches wherever necessary.

3) Figures to the right indicate full marks.

4) Assume suitable data, if necessary.

5) Preferably write the answers in sequential order.


Q.1 Attempt any FIVE of the following. [10]

a) List features of Android operating system. (Refer section 1.2)


b) State the steps for creating the Virtual device. (Refer section 2.3)
c) List and explain files associated with build.gradle. (Refer section 3.1.2)
d) List all attributes to develop a radio button. (Refer section 4.1.6)
e) List different methods used in Intent. (Refer section 5.1.3)
f) Define services in Android operating system. (Refer section 5.4)
g) Enlist the steps for publish the Android application. (Refer section 6.4.3)
Q.2 Attempt any THREE of the following. [12]

a) With neat diagram, show the major components of Android stack. (Refer section 1.4)
b) Differentiate between JVM and DVM. (Refer section 2.5)
c) Explain the activity life cycle. (Refer section 5.2)
d) What are the benefits of Content providers. (Refer section 5.3)
Q.3 Attempt any THREE of the following. [12]

a) Explore the Steps to install and configure Android Studio and SDK. (Refer section 2.6.3)
b) Write an xml tag for the determinate progress bar. (Refer section 4.1.9)
c) Define SQLite. Explain example table for SQLite store data in tables. (Refer section 5.8)
d) Define activity. Explain the steps for creating activities. (Refer section 5.2)
Q.4 Attempt any THREE of the following. [12]

a) Write a program to show the following output. (Refer section 4.1.9)

(S - 3)
Mobile Application Development S-4 Solved Sample Papers

b) Write a program to create a first display screen of any search engine using Auto Complete Text View.
(Refer section 4.1.1.1)
c) Write steps to create a content provider in android applications. (Refer section 5.3.1)
d) Write a program to display the following output. (Refer section 5.2)

e) Develop an application to send and receive SMS. (Write ONLY Java and permission tag in manifest file).
(Refer section 6.2.2.1)
Q.5 Attempt any TWO of the following. [12]

a) Write a program to insert data in SQLite database using AsyncTask. (Refer section 5.5.5)
b) Write a program to capture an image using camera and display it. (Refer section 5.6.1)
c) Write a program to draw a route between two locations. (Refer section 6.2.6)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development S-5 Solved Sample Papers

Q.6 Attempt any TWO of the following. [12]

a) Develop an application to store student details like roll no., name, branch, marks, percentage and retrieve
student information using roll no. in SQLife database. (Refer section 5.8.2)
b) Write a program to create two screens. First screen will take one number input from user. After click on
Factorial button, second screen will open and it should display factorial of the same number. Also specify which
type of intent you will use in this case. (Refer section 5.1)
c) Develop a simple calculator using table layout. (Refer section 3.3.4)

qqq

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Mobile Application Development S-6 Solved Sample Papers

Notes

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Books available @

MUMBAI NASHIK
Student Agencies Pvt. Ltd. Rahul Book Centre
Ph. - 022 - 40496161 / 31 Ph. - 0253 - 27424287
Vidyarthi Sales Agencies Maharashtra Pustak Bhandar
Ph. - 022 - 23829330 Ph. - 0253 - 2317506
022 - 23851416 / 23867279 New India Book House
Bharat Sales Ph. - 9623123458
Ph. - 022 - 23821307 / 7580 Anmol Pustakalaya
Ph. - 9822306289
AHMEDNAGAR Anmol Books
Ph. - 0253 - 2505501
Shripad Granth Bhandar
Ph. - 9922664979 Om Pustakalaya
Ph. - 9422246809
SANGAMNER Pragati Books & Stationers
Ph. - 7721014040
Amrut Book Stall
Ph. - 9850663354 New Om Stationers
& General Stores
NARAYANGAON Ph. - 0253 - 2378874
Shri Ganesh Book Depot
Sunil General Stores
Ph. - 9890335806
Ph. - 9850725770
Eakveera Books
KOPARGAON Ph. - 9422754746

Mauli Books & General Store Yuvraj Books & Stationers


Ph. - 9890451467 Ph. - 9850725770

Kohinoor Book Stall New Anand Pustakalaya


Ph. - 9371719996 Ph. - 9881540440 / 7720054040

KARAD JALGAON
Archana Bazar Parvati Traders
Ph. - 7588065287 Ph. - 9422277738

(i)
R

TECHNICAL PUBLICATIONS - An up thrust for knowledge


SANGALI BARAMATI
G. R. Tamhankar Sankalp World
Ph. - 9422041091 Ph. - 7020837475 / 9765851000
Mirji Book House
Ph. - 9422613980 YEOTMAL
Sankalp Enterprises
Shri Aadhinath Book Centre
Ph. - 9823619823
Ph. - 9422866072
KOLHAPUR
NAGPUR
Granth The Book Word
Ph. - 9922295522 Venus Book Centre
Ph. - 9975768899
DHULE
AURANGABAD
Kushal Book Shop
Ph. - 02562 - 280468 New Arihant Stationers
& Book Centre
LATUR Ph. - 9850697469 / 9420263132
Umade Book Centre
Gatagat Stores Ph. - 9881218686
Ph. - 9422611032
Maya Book Centre
Ph. - 9766660310
AKOLA Vidhyarthi Bhandar
Harne Book Depot Ph. - 9764422777
Ph. - 9922669647
BULDHANA
AMRAVATI
Agrasen Sales Corporation
Navyug Book Stall Ph. - 9422181542 / 9422882542
Ph. - 7212672664

(ii)
R

TECHNICAL PUBLICATIONS - An up thrust for knowledge

You might also like