0% found this document useful (0 votes)
8 views171 pages

Introduction to Mobile Operating Systems

The document provides an introduction to mobile programming, focusing on mobile operating systems, particularly Android. It covers the evolution of mobile OS, the architecture of Android, its components, and the development environment required for Android applications. Key topics include the history of Android, its architecture layers, and the structure of an Android project.

Uploaded by

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

Introduction to Mobile Operating Systems

The document provides an introduction to mobile programming, focusing on mobile operating systems, particularly Android. It covers the evolution of mobile OS, the architecture of Android, its components, and the development environment required for Android applications. Key topics include the history of Android, its architecture layers, and the structure of an Android project.

Uploaded by

birhanfentie64
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Chapter

One
Introduction to Mobile
Programming

1
Introduction
 Mobile Devices need some type of
Operating System to run its services.
 Earlier OS were fairly simple, since they
supported limited capabilities.
 Modern devices however, added many of
the features of a full-fledged desktop
computer like CPU, GPU, large storage,
multitasking, multipurpose communication
device etc.
 Modern OS combines a PC with other
mobile specific features like
Bluetooth, GPS, speech recognition,
video camera, infrared etc, so mobile
OS had to grow to support all these
features. 2
What is Mobile OS?
A software platform on top of which
other apps can run on.
 Experienced a 3 phase evolution
 PC oriented, Embedded System Oriented
and Smart-phone oriented evolution
 The architecture goes from complex to simple or
something in between
 Evolution has driven by tech advancements in HW,
SW and the Internet
 Resulted in a variety of OS platforms available on the
Some of the mobile operating
market

systems are:
iOS:- Developed by Apple inc. and distributed
exclusively for Apple Hardware

Windows Phone:- A proprietary software Smartphone
OS developed by Microsoft
 Android:- Developed by Open Handset Alliance (OHA),
Led by Google
3
What is Android?
 Android is a mobile operating system
currently developed by Google, based on
the Linux kernel and designed primarily
for touch screen mobile devices such
as smart phones and tablets.
 Android offers a unified approach to
application development for mobile
devices which means developers need to
develop only for Android, and their
applications should be able to run on
different devices powered by Android.
 Android is an open-source operating
system named Android.
4
Cont…
Android is a software stack for
mobile devices that includes an
operating system, middleware
and key applications.
The Android SDK provides the
tools and APIs necessary to
develop applications on the Android
platform using the Java
Programming language.

5
History and Version of Android
The history and versions of android
are interesting to know.
The code names of android ranges
from A to L currently, such as
Aestro, Blender, Cupcake,
Donut, Eclair, Froyo,
Gingerbread, Honeycomb, Ice
Cream Sandwitch, Jelly Bean,
KitKat and Lollipop.

6
Cont…
Let's understand the android history in a sequence.
 Initially, Andy Rubin founded Android Incorporation
in Palo Alto, California, United States in October,
2003.
 In 17th August 2005, Google acquired android
Incorporation. Since then, it is in the subsidiary of
Google Incorporation.
 The key employees of Android Incorporation
are Andy Rubin, Rich Miner, Chris White and
Nick Sears.
 Originally intended for camera but shifted to smart
phones later because of low market for camera only.
 Android is the nick name of Andy Rubin given
by coworkers because of his love to robots.
 Google formed Open Handset Alliance (OHA) on 5th
November 2007.
7
Cont…
What is Open Handset Alliance?
 The Open Handset Alliance is a group of 84
technology and mobile companies who have
come together to accelerate innovation in
mobile and offer consumers a richer, less
expensive, and better mobile experience.
Which was the first commercially
available Smartphone running Android?
 The first commercially available
Smartphone running Android was the
HTC Dream it came to the market as the
T-Mobile G1 in the USA, released on
October 22 2008.
8
Android Architecture
Android is a software stack.
 Android software stack is categorized into
five parts:

9
Applications
Applications layer is the top
most layer of Android
Architecture.
All applications using android
framework uses android runtime
and libraries, while android runtime
and native libraries are using Linux
Kernel.
Android applications can be
developed using languages such
as C++, C#, Java etc.
But the official language is Java. 10
Application Framework:
The android framework is the set of
API’s that allow developers to
quickly and easily write apps for
android phones.
Android framework includes Android
API's such as UI (User Interface),
telephony, resources, locations,
Content Providers (data) and
package managers.
It provides a lot of classes and interfaces
for android application development.
Application developers are allowed to
make use of these services in their
11
Native

Applications/Libraries:
Just by using Java we cannot interact with
native applications.
 (Here native applications means that programs
written in some other languages like C, C++,
Assembly language which are specific to
hardware and operating system).
 Thus we need the support of native libraries for
interacting with such low level media
components.
 On the top of linux kernel, there are Native
libraries such as WebKit, OpenGL, FreeType,
SQLite, Media, C runtime library (libc) etc.
 The WebKit library is responsible for
browser support, SQLite is for database,
FreeType for font support, Media for playing
and recording audio and video formats. 12
Android Runtime
It comprises of Dalvik Virtual
Machine and Core Libraries
which is responsible to run
android application.
DVM is like JVM but it is
optimized for mobile devices.
It consumes less memory and
provides fast performance.

13
Linux Kernel
In android the operating system is Linux
Kernel.
It is the heart of android architecture that
exists at the root of android architecture.
Linux kernel is responsible for device
drivers, power management, memory
management, device management
and resource access.
You can find the Linux Kernel version
running on your device under “About
phone” or “About tablet” in Android’s
settings.

14
Functions of Linux Kernel/ Operating
System
Memory Management: Allocate a
memory to a new file, Free the memory
when a specific file is deleted etc
Power Management: providing power
to various devices like Bluetooth, camera
etc
Resource Management: It provides
resources to each process, thus providing
the ability to do multiple operations at
the same time. i.e. Surfing Internet,
Listening Songs etc
Driver Management: It handles
installation of various drivers.
15
Android Compilers
 JDK (Java Development Kit) compile our Java
code and it produce a file called .class file.
 It is also called as Java bytecode.
 Java Bytecode is a platform independent code
because it can run on multiple platforms.
 In android Dex compiler take all the .class file as
input and it produce a single lightweight file
called .dex file.
 Dex compile produces a single .dex file for
multiple .class files.
 Dex is termed as Dalvik Executable Code.
 DVM takes this single .dex file as input and generates
the final machine code.
 With Android version 2.2(Froyo) Google introduced
JIT(Just in Time) compilation in Dalvik.
 Till Android Version 5.0(Lollipop) Dalvik was the
runtime used by Android which is being replaced by16
Cont…
Why do we need a .dex file when actually
even .class file is platform independent?
 DVM is Register based which is designed to run
on low memory unlike JVM which is stack based.
 Thus though DVM we are able to achieve small
memory footprint with higher battery life.
 Java tools are free but the JVM is not free, so
that android developers from Google have made
their own virtual machine and made it as free.
ART vs Dalvik
 ART is a new Android runtime which was
introduced experimentally in the 4.4
release KitKat.
 If you have KitKat then you can see the preview
in “setting >Developer Option>Select Runtime”.17
Cont…
Why did Google switched from Dalvik to
ART?
 Android apps are deployed in Dalvik bytecode,
which is portable, unlike native code.
 In order to be able to run the app on a
device, the code has to be compiled to
machine code.
 Dalvik is based on JIT compilation.
 It means that each time you run an app, the
part of the code required for its execution is
going to be translated (compiled) to machine
code at that moment.
 . Since JIT compiles only a part of the code, it
has a smaller memory footprint and uses less
physical space on the device. 18
Cont…
 ART, on the other hand compiles the intermediate
language, Dalvik bytecode, into a system
independent binary.
 The whole code of the app will be pre-compiled
during installation (once), thus removing the lag
that we see when we open an app on our device.
 With no need for JIT compilation, the code should
execute much faster.
 Except for the potential speed increase, the use of
ART can provide an important secondary benefit.
 As ART runs app machine code directly (native
execution), it does not hit the CPU as hard as Just-
in-Time code compiling on Dalvik.
 Less CPU usage results in less battery drain,
which is a big plus for portable devices in general.
19
Android Application
Components
Activities:
 An activity in Android represents a single screen with which a user can
interact with.
 Each Activity in android will be subclass of Activity class defined in Android
SDK.
 Thus public class MainActivity extends Activity (if MainActivity is the name of
the Activity).
Services:
 Long running background process without any need of user interaction is
known as Service.
 Each service in android will be subclass of service class defined in Android
SDK.
 Thus public class MyService extends Service (if MyService is the name of the
service).
Broadcast Receiver:
 They handle communication between Android OS and applications.
 For example the notification that the device battery is low, the sign of
earphone as soon as you plug the headset.
 Although broadcast receivers don’t display a user interface, they may create
a status bar notification to alert the user when a broadcast event occurs.
Content Provider:
 content providers are used to share data between the applications.
 In android the data cannot be shared directly between the two applications.
20
Additional Components
There are additional components which
will be used in the construction of above
mentioned entities, their logic, and wiring
between them.
These components
 Fragments: are: a behavior or a
Represent
portion of user interface in an Activity.
 Views: UI elements that are drawn onscreen
including buttons, lists forms etc.
 Layouts: View hierarchies that control
screen format and appearance of the views.
 Intents: Messages wiring components
together.
 Resources: External elements, such as
strings, constants and drawable pictures.
 Manifest: Configuration file for the21
Getting Started
 In order to write an Android application,
we need a Java Development Kit (JDK),
Java Runtime Environment (JRE) and
development environment.
 The common Android application
development environments are Android
Studio, Eclipse and NetBeans.
 But officially Android Studio is the
recommended IDE for developing Android
Projects.
 Android Studio is a very useful tool made
by Google for all Android Developers.
 Android Studio includes everything you
22
Cont…
Included in the download kit, are the
Software Development Kit (SDK), with all
the Android libraries we may need, and
the infrastructure to download the many
Android emulator instances, so that we
can initially run our application, without
needing a real device.
Android Emulator is used to run, debug
and test the android application.

23
Android Project Structure
When you start a new project, Android
Studio creates the necessary structure
for all your files and makes them visible
in the project window on the left side of
the IDE click View>Tool
Windows>Project.
By default, Android Studio displays our
project files in the Android view.
Android
 Android Appproject contains six basic
Module
elements:
 Android [Link]
 Android Java
 Android Resource (res)
 Android Strings
 Android Styles 24
Android App Module
 When you create a new project, the default module
name is “app”.
 A module is a collection of source files and build
settings that allow you to divide your project into
discrete units of functionality.
 A Project can have one or more modules and one
module may use another module as a dependency.
 Each module can be independently built, tested and
debugged.
 Module provides a container for your app’s source
code, resource files, and app level settings such as
the module-level build file and Android Manifest file.
 In the create new module window, Android Studio
offers different app modules such as Phone & Tablet,
Android Wear, Android TV and Glass Modules.
 Each module provides essential files and some code
templates that are appropriate for the corresponding25
Android [Link]
Android [Link] describes the
fundamental characteristics of an
app and each of its components.
It works as an interface between
your android OS and your
application, so if you forget to
declare your components in this file
then it will not be considered by the
OS.

26
Android Java
It contains the Java source code
files separated by package names
and JUnit test code. All the Activity
classes are stored inside java folder.
For e.g. The Activity class called
[Link] is stored in this
directory under the package name
you mentioned in the wizard.

27
Android Resource (res)
It contains all non-code resources, such
as xml layouts, UI strings and bitmap
images, divided into corresponding sub-
directories.
Some of the examples
 Animation of resource defines
Resources- types
are:predetermined animations. Animations are
saved in res/anim/ and accessed from the
[Link] class. Frame animations are saved in
res/drawable/ and accessed from the
[Link] class.
 Color State List Resource-it defines color
resources that changes based on the view
state. It is saved in res/color/ and accessed
from the [Link] class
 Drawable Resource- defines various28
Cont…
Layout Resource- defines the layout
for your application UI. It is saved in
res/layout/ and accessed from the
[Link] class.
Menu Resource- defines the contents
of your application menus. It is saved in
res/menu/ and accessed from the
[Link] class.
String Resource- defines string, string
arrays and plurals (and include string
formatting and styling). It is saved in
res/values/ and accessed from the
[Link], [Link] and [Link] classes.
Style Resource- defines the look and29
Android Strings
A string resource provides text
strings for your application with
optional text styling and formatting.
Types of resources that can provide
your application with strings:
String: XML resource that provides
a single string.
String Array: XML resource that
provides an array of strings.

30
Android Styles
A style resource defines the format
and look for a UI.
It can specify properties such as
height, padding, font color, font
size, background color etc.
Styles in Android share a similar
philosophy to cascading style
sheets in web design i.e they allow
you to separate the design from the
content.

31
Chapter-2
Android Layout and
UI Widgets

By: Ins Zigiju N.


View and View Groups
What are Views?
 Anything, which occupies a rectangular area
on the screen and is responsible for drawing
and event handling, is known as a view.
 Thus every UI element is subclass of view,
to be more precise of [Link].
 The android SDK provides a set of pre-built
views that can be used to construct a user
interface, for example buttons, checkbox,
EditText etc. which are also known as
widgets.
34

By: Zigiju N
Cont…
Widgets:
 can be thought of as a pre-built control through
which the user interacts with your application.
 There is nothing such as widget class in android.
 It simply means that the class is in
[Link] package in android.
 Android contains the following commonly used
View subclasses: TextView, EditText, ImageView,
ProgressBar, Button, ImageButton, ChechBox etc.
 We can also create our widget by extending view
or any of its subclass inside [Link].

35

By: Zigiju N
Cont…
What are ViewGroup?
 The ViewGroup is a subclass of View
([Link]) and provides invisible
container that hold other views or other
ViewGroups and define their layout properties.
 Thus all the Layouts and Containers inherit
from ViewGroup.
 The view group is the base class for
layouts and views containers.
 Android contains the following commonly used
ViewGroup subclasses: LinearLayout,
RelativeLayout, ListView, GridView etc.
36

By: Zigiju N
Layout and its types
Layouts are subclasses of ViewGroup
which specifies how a view should
be arranged inside the
viewgroups.
It defines
 Declarethe visualinstructure
UI elements XML for
 Instantiate layout elements at runtime
a user interface.
You can create layouts in two ways:-

37

By: Zigiju N
Cont…
 The standard Layouts are:
 LinearLayout: A layout that arranges its
children in a single column or a single row. The
direction of the row can be set by calling
setOrientation( ).
 RelativeLayout: A layout where the positions
of the children can be described in relation to
each other or to the parent.
 FrameLayout: It is used to block out an area
on the screen to display a single item.
 TableLayout: A layout that arranges its
children into rows and columns.
38

By: Zigiju N
Cont…
LinearLayout:
 A layout that arranges its children in a single
column or a single row.
 The direction of the row can be set by calling
setOrientation( ).
 Linear layout is a view group that aligns all children
in a single direction, vertically or horizontally.
 Layout direction is specified by

android:orientation=”horizontal” or
android:orientation=”vertically”
attribute.
 LinearLayout horizontal arranges the elements
horizontally in the LinearLayout.
39

By: Zigiju N
Cont…
RelativeLayout:
A layout where the positions of the
children can be described in relation to
each other or to the parent.
RelativeLayout lays out elements
based on their relationships with one
another, and with the parent container.
This is arguably the most complicated
layout and we need several properties
to actually get the layout we want.
40

By: Zigiju N
Cont…
Relative to container:
 These properties will layout elements relative to the parent
container.
 android:layout_alignParentBottom-places the element on the
bottom of the container.
 android:layout_alignParentLeft-places the element on the left
side of the container.
 android:layout_alignParentRight-places the element on the
right side of the container.
 android:layout_alignParentTop-places the element on the top of
the container.
 android:layout_centerHorizontal-centers the elements
horizontally within its parent container.
 android:layout_centerInParent- centers the elements both
horizontally and vertically within its parent container.
 android:layout_centerVertical- centers the elements vertically
within its parent container..
41

By: Zigiju N
Cont…
Relative to other Elements:
 These properties allow you to layout elements relative to other
elements on screen.
 The value for each of these elements is the id of the element you are
using to layout the new element.
 Each element that is used in this way must have an ID defined using
android:id=”@_id/xxxxx” where xxxxx is replaced with the
desired id. You use “@id/xxxxx” to reference an element by its id.
 One thing to remember is that referencing an element before it has
been declared will produce an error.
 android:layout_above- places an element above the specified
element.
 android:layout_below- places an element below the specified
element.
 android:layout_toLeftOf- places an element to the left of the
specified element.
 android:layout_toRightOf- places an element to the right of the
specified element.
42

By: Zigiju N
Cont…
Relative with other Elements:
 These properties allow you to specify how elements
are aligned in relation to other elements.
 android:layout_alignBaseline- aligns baseline of the
new element with baseline of the specified element.
 android:layout_alignBottom- aligns bottom of the
new element in with bottom of the specified element.
 android:layout_alignLeft- aligns left edge of the
new element with left edge of the specified element.
 android:layout_alignRight- aligns right edge of the
new element with right edge of the specified element.
 android:layout_alignTop- places top of the new
element in alignment with the top of the specified
element.
43

By: Zigiju N
Cont…
FrameLayout:
 It is used to block out an area on the screen to
display a single item.
 FrameLayout is designed to display a single item
at a time.
 You can have multiple elements within a
FrameLayout but each element will be positioned
based on the top left of the screen.
 Elements that overlap will be displayed
overlapping.
 FrameLayout can become more useful when
elements are hidden and displayed
programmatically. 44

By: Zigiju N
Cont…
 FrameLayout can become more useful when
elements are hidden and displayed
programmatically.
 You can use the attribute android:visibility in
the XML to hide specific elements.
 You can even call setVisibility method from
the code to accomplish the same thing.
 The three available visibility values are
visible, invisible (does not display but still
takes up space in the layout) and gone (does
not display and does not take space in the
layout).
45

By: Zigiju N
Layout Attributes
 Each layout has a set of attributes which define the visual
properties of that layout.
 There are few common attributes among all the layouts and there
are other attributes which are specific to that layout.
 Following are common attributes and will be applied to all the
layouts:
 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
 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.
46

By: Zigiju N
Cont…
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.
android:paddingTop- This is the top padding filled for the
layout.
android:paddingBottom-This is the bottom padding filled
for the layout.
47

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

By: Zigiju N
View Identification
A view object may have a unique ID assigned to it
which will identify the View uniquely within the tree.
 The syntax for an ID, inside an XML tag is :

android:id="@+id/my_button"
 Following is a brief description of @ and + signs −
 The at-symbol (@) at the beginning of the string
indicates that the XML parser should parse and
expand the rest of the ID string and identify it as an
ID resource.
 The plus-symbol (+) means that this is a new
resource name that must be created and added to
our resources.
 To create an instance of the view object and capture
itButton
from the layout, use the following − 49
myButton = (Button)
findViewById([Link].my_button);
By: Zigiju N
Android User Interface (UI) widgets
 Android UI widgets are input controls which are
used to build a user interface for your
application.
 Input controls are the interactive components in
your app's user interface.
 A View is an object that draws something on the
screen that the user can interact with such as
Text fields, Buttons etc and a ViewGroup is an
object that holds other View (and ViewGroup)
objects in order to define the layout of the user
interface.
 The following picture shows some of the input
controls.
50

By: Zigiju N
Cont…
Android provides various UI controls
that allow you to build the graphical
user interface for your app.
These are:-
TextView, EditText,
AutoCompleteTextView, Button,
ImageButton, CheckBox,
ToggleButton, RadioButton,
RadioGroup, ProgressBar, Spinner
, TimePicker, DatePicker etc.
51

By: Zigiju N
Create UI Controls
Android EditText
 EditText view is a subclass of the TextView that allows
users to edit its text content.
 It is also known as a text field in other platforms.
 It can be either single line or multi-line.
 Touching a text field places the cursor and automatically
displays the keyboard.
 In addition to typing, text fields allow for a variety of
activities such as text selection (cut, copy, paste) and
data look-up via auto-completion.
 You can specify the type of keyboard you want for your
EditText object with the android:inputType attribute.
 For example, if you want the user to input a phone
number, you should use the phone input type.
52

By: Zigiju N
Cont…
Example:
<EditText
android:id="@+id/search "
android:layout_width="fill_parent "

android:layout_height="wrap_content"
android:hint="Search Tex"
android:inputTYpe="text"
android:imeOptions="actionSend"
/>
53

By: Zigiju N
Cont…
There are different input types, the
most common are:
text- displays a normal text keyboard
textEmailAddress- displays a normal
text keyboard with the @ character
textUri- displays a normal text
keyboard with the / character
number- displays a basic number
keypad
phone- displays a phone style keypad
54

By: Zigiju N
Cont…
Retrieving / Getting the Value
From EditText In Java Class:
Below is the example code of
EditText in which we retrieve the
value from an EditText in Java class.
EditText simpleEditText = (EditText) findViewById([Link]);
We
String have =used
editTextValue this code in the
[Link]().toString();

example you will find at the end of


this post.

55

By: Zigiju N
Cont…
Buttons
 In Android, Button represents a push button.
 A Push buttons can be clicked, or pressed by the user
to perform an action.
 There are different types of buttons used in android
such as CompoundButton, ToggleButton, RadioButton.
 Button is a subclass of TextView class and compound
button is the subclass of Button class.
 On a button we can perform different actions or
events like click event, pressed event, touch
event etc.
 Android buttons are GUI components which are
sensible to taps (clicks) by the user.
56

By: Zigiju N
Cont…
Example: the following example shows
how to create a button via a layout xml
file.
<Button
android:id="@+id/btn1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display"
android:onClick="btnClick()"
/>
57

By: Zigiju N
Cont…
 android:id- provides a unique identification to a UI
element.
 usually done by findViewByID( ) method
 android:layout_width & android:layout_height-
defines the size that the UI element should
occupay.
 android:text- defines the text which the UI
element should display.
 If you want to create an image button use
android:drawableLeft property and set its value
“@mipmap/ic_launcher”. (Where mimap is the
directory in which the image is stored and
ic_launcher is name of the image.
58

By: Zigiju N
Android - Event Handling
Events are a useful way to collect data
about a user's interaction with
interactive components of applications.
Like button presses or screen touch etc.
The Android framework maintains an
event queue as first-in, first-out (FIFO)
basis.
You can capture these events in your
program and take appropriate action as
per requirements.
59

By: Zigiju N
Cont…
 There are three concepts related to Android Event Management

Event Listeners:
 An event listener is an interface in the View class that contains
a single callback method.
 These methods will be called by the Android framework when
the View to which the listener has been registered is triggered
by user interaction with the item in the UI.
Event Listeners Registration:
 Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is
called when the Event Listener fires the event.
Event Handlers:
 When an event happens and we have registered an event
listener for the event, the event listener calls the Event
Handlers, which is the method that actually handles the event.
60

By: Zigiju N
Cont…
Event Listeners Registration
Event Registration is the process by
which an Event Handler gets
registered with an Event Listener so
that the handler is called when the
Event Listener fires the
 Using an Anonymous Inner Class
event.
Though
Activity there are severalthe
class implements tricky ways
Listener
tointerface.
register your event listener for any
 Using Layout file activity_main.xml to specify
event, but some of them are :
event handler directly.
61

By: Zigiju N
Styles and Themes
If you already know about Cascading
Style Sheet (CSS) in web design then to
understand Android Style also works
very similar way.
There are number of attributes
associated with each Android widget
which you can set to change your
application look and feel.
A style can specify properties such as
height, padding, font color, font size,
background color, and much more.
62

By: Zigiju N
Cont…
Android styles:
 A style is defined in an XML resource that is
separate from the XML that specifies the layout.
 This XML file resides under res/values/ directory
of your project and will have <resources> as the
root node which is mandatory for the style file.
 The name of the XML file is arbitrary, but it must
use the .xml extension.
 You can define multiple styles per file using
<style> tag but each style will have its name
that uniquely identifies the style.

63

By: Zigiju N
Cont…
 Android style attributes are set using <item> tag as shown
below:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
 The value for the <item> can be a keyword string, a hex color,
a reference to another resource type, or other value depending
on the style property. 64

By: Zigiju N
Cont…
Android supports style Inheritance in
very much similar way as cascading
style sheet in web design.
You can use this to inherit properties
from an existing style and then
define only the properties that you
want to change or add.

65

By: Zigiju N
Cont…
Android Themes
Hope you understood the concept of
Style, so now let's try to understand what
is a Theme.
A theme is nothing but an Android style
applied to an entire Activity or application,
rather than an individual View.
Thus, when a style is applied as a theme,
every View in the Activity or application
will apply each style property that it
supports.
66

By: Zigiju N
thank you

any q?
67

By: Zigiju N
Chapter-3
Activity, Fragments,
Intent and Services

By: Ins Zigiju N.


May, 2022
Activity
 In android, Activity represents a single screen with
a user interface (UI) of an application and it will act
as an entry point for users to interact with an app.
 An activity is the single screen in android. It is
like window or frame of Java.
 By the help of activity, you can place all your UI
components or widgets in a single screen.
 From the multiple activities in android app, one
activity can be marked as a main activity and that
is the first screen to appear when we launch the
application.
 In android app each activity can start another
activity to perform different actions based on our
requirements. 69

By: Zigiju N
Cont…
To use activities in application we
need to register those activities
information in our app’s manifest file
([Link]) and need to
<?xml version="1.0" encoding="utf-8"?>
<manifest …..>
manage<application
activity …..>
life cycle properly.

<activity android:name=".MainActivity"
>
…….
…….
</activity>
…….
70
</application>
</manifest> By: Zigiju N
Cont…
The activity
attribute android:name will
represent the name of class and we
can also add multiple attributes like
icon, label, theme, permissions, etc.
to an activity element based on our
requirements.
 In android application, activities can
be implemented as a subclass
of Activity class like as shown below.
71

By: Zigiju N
Cont…
import [Link];
import [Link];
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceS-
tate) {
[Link](savedInstanceState);
setContentView([Link]);
}
}
72

By: Zigiju N
Cont…
There is a sequence of callback
methods that start up an activity and
a sequence of callback methods that
tear down an activity as shown in the
below Activity life cycle diagram:

73

By: Zigiju N
Cont…

74

By: Zigiju N
Cont…
• The Activity class defines the following call backs
i.e. events. You don't need to implement all the
callbacks methods.
[Link] Callback & Description
onCreate()
1 This is the first callback and called when the
activity is first created.
onStart()
2 This callback is called when the activity
becomes visible to the user.
onResume()
3 This is called when the user starts interacting
with the application.
75

By: Zigiju N
Cont…
[Link] Callback & Description
onPause()
The paused activity does not receive user input
4 and cannot execute any code and called when
the current activity is being paused and the
previous activity is being resumed.
onStop()
5 This callback is called when the activity is no
longer visible.
onDestroy()
6 This callback is called before the activity is
destroyed by the system.
onRestart()
7 This callback is called when the activity
76
restarts after stopping it
By: Zigiju N
Fragment
A Fragment represents a reusable portion of
your app's UI.
 A fragment defines and manages its own layout,
has its own lifecycle, and can handle its own input
events.
 Fragments cannot live on their own--they must be
hosted by an activity or another fragment.
 A Fragment is a combination of an XML layout
file and a java class much like an Activity .
 Using the support library, fragments are supported
back to all relevant Android versions.
 Fragments encapsulate views and logic so that it
is easier to reuse within activities.
77

By: Zigiju N
Cont…
A Fragment is a piece of an application's user
interface or behavior that can be placed in
an Activity.
 Interaction with fragments is done through
FragmentManager, which can be obtained via
[Link](), and
[Link]().
 A Fragment is closely tied to the Activity it is in,
and can not be used apart from one.
 Though Fragment defines its own lifecycle, that
lifecycle is dependent on its activity: if the activity
is stopped, no fragments inside of it can be
started; when the activity is destroyed, all
78
fragments will be destroyed.
By: Zigiju N
Cont…
Following are important points about fragment −
 A fragment has its own layout and its own behaviour
with its own life cycle callbacks.
 You can add or remove fragments in an activity while the
activity is running.
 You can combine multiple fragments in a single activity
to build a multi-pane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of
its host activity which means when the activity is
paused, all the fragments available in the activity will
also be stopped.
 A fragment can implement a behaviour that has no user
interface component.
 Fragments were added to the Android API in Honeycomb 79
version of Android which API version 11.
By: Zigiju N
Fragment Life Cycle
Android fragments have their own life
cycle very similar to an android
activity.

80

By: Zigiju N
Cont…
 onAttach(): The fragment instance is associated
with an activity instance. The fragment and the
activity is not fully initialized.
 onCreate(): The system calls this method when
creating the fragment.
 onCreateView(): The system calls this callback
when it's time for the fragment to draw its user
interface for the first time.
 onActivityCreated(): The onActivityCreated() is
called after the onCreateView() method when the
host activity is created.
 Activity and fragment instance have been
created as well as the view hierarchy of the 81
activity.
By: Zigiju N
Cont…
 onStart(): The onStart() method is called once
the fragment gets visible.
 onResume(): Fragment becomes active.
 onPause(): The system calls this method as the
first indication that the user is leaving the
fragment.
 onStop(): Fragment going to be stopped by
calling onStop()
 onDestroyView(): Fragment view will destroy
after call this method
 onDestroy(): onDestroy() called to do final
clean up of the fragment's state but Not
guaranteed to be called by the Android platform.82

By: Zigiju N
Intents
 Android uses Intent for communicating
between the components (such as activities
, services, broadcast receivers and
content providers) of an Application and also
from one application to another application.
 An intent is to perform an action on the
screen.
 It is mostly used to start activity, send
broadcast receiver, start services and send
message between two activities.
 There are two intents available in android as
Implicit Intents and Explicit Intents. 83

By: Zigiju N
Cont…
 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.
 The dictionary meaning of intent
is intention or purpose. So, it can be
described as the intention to do action.
 The LabeledIntent is the subclass of
[Link] class.
84

By: Zigiju N
Cont…
Android intents are mainly used to:
 Start the service
 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.

85

By: Zigiju N
Types of Intents
 There are two types of intents in android: implicit
and explicit.
1) Implicit Intent
 Implicit Intent doesn't specify the name of the
component.
 In such case, intent provides information of
available components provided by the system that
is to be invoked.
 We just specify the Action which has to be
performed and further this action is handled by the
component of another application.
 For example, you may write the following code to
Intentthe
view intent=new Intent(Intent.ACTION_VIEW);
webpage.
[Link]([Link]("http:// 86
[Link]"));
startActivity(intent); By: Zigiju N
Cont…
2) Explicit Intent
Explicit Intent specifies the component.
Explicit Intents are used to connect the
application internally.
In Explicit we use the name of component
which will be affected by Intent.
In such case, intent provides the external
class to be invoked.
Example:

Intent inte = new Intent(getApplicationContext(), [Link]);


startActivity(inte);
87

By: Zigiju N
Android Service
Android service is a component that is
used to perform operations on the
background such as playing music, handle
network transactions, interacting content
providers etc.
It doesn't have any UI (user interface).
The service runs in the background
indefinitely even if application is
destroyed.
Moreover, service can be bounded by a
component to perform interactivity and
inter process communication (IPC). 88

By: Zigiju N
Cont…
An Android service is a component
that is designed to do some work
without a user interface.
A service might download a file, play
music, or apply a filter to an image.
Services can also be used for inter
process communication (IPC) between
Android applications.

89

By: Zigiju N
Types of Android Services
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.
Once there are no more clients bound
to the service, Android will shut the
service down.
90

By: Zigiju N
Cont…
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.
 Unlike a service, which can concurrently handle
multiple calls, an IntentService is more like
a work queue processor – work is queued up
and an IntentService processes each job one at
a time on a single worker thread.
 Typically, an IntentService is not bound to an
Activity or a Fragment. 91

By: Zigiju N
Cont…
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.
Unlike a bound service, a started service
does not have any clients directly bound to
it.
For this reason, it is important to design
started services so that they may be
gracefully restarted as necessary. 92

By: Zigiju N
Cont…
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.
A client component may or may not be
bound to the hybrid service.
A hybrid service will keep running until it is
explicitly told to stop, or until there are no
more clients bound to it. 93

By: Zigiju N
Characteristics of Mobile Application
Simplicity
 Many people have short attention spans and if you make
your app difficult to navigate then they will lose interest
fast.
 If your customer cannot access their information quickly
and easily, they will become frustrated and do it another
way – possibly by using a competitor’s app.
Speed
 Fast loading screens are vital. No one likes waiting,
particularly when all they have to look at is a screen-
loading symbol and this frustration soon gives way to
boredom resulting in a decision to seek something better.
 Speed means an appropriate set of graphics and not
fetching large tables and databases. Keep it simple and
keep it quick.
94

By: Zigiju N
Cont…
Good image resolution
 While you have to balance app speed against
functionality and resolution, you have to ensure
that what you have on screen is sufficiently
detailed to make the user experience worthwhile.
Flexibility
 There are three main mobile operating systems –
iOS, Android, and Windows – and in order to
achieve the best out of your app, it needs to be
available on all of these.
 Android apps are easy to upload to the PlayStore,
but iOS needs to be tried and tested by Apple
before they are allowed on the App Store.
95

By: Zigiju N
Cont…
Security
Internet security is becoming an
ever-increasing issue and the same
applies for your app.
With many applications storing
personal andinto
 Place malware sensitive
apps and ontoinformation or
devices where it can
credit and
access data debit
and stealcard details,
screen lock passcodes security
 Intercept sensitive information travelling over the
is an absolute must.
network
 Steal customer data for identity theft or fraud.
Hackers
 Get hold may attempt
of private to:
business assets

96

By: Zigiju N
Cont…
Search options
 It sounds simple but many apps miss this important
feature considering this is something that many
users make use of.
 The ability to search either the app or the internet
is important and while it’s not going to work so
much for game-based apps, it’s essential for the
business and social variety.
Bright and bold colour schemes
 Fundamentals such as eye-grabbing colour
schemes are going to pull your customers in.
 Pay attention to complementary colours from the
colour wheel and you will end up with an app that
looks stylish and professional at the same time. 97
By: Zigiju N
Cont…
Push notifications
 Easier to send than emails and less likely to end up in a
spam folder, push notifications can be text, graphic, or a
combination of both to send your users content that they
may be interested in.
 Relevant and personalised push messaging is much
better than unsolicited messages since they are aimed
solely at the particular user and likely to be of interest to
them.
User feedback
 Feedback is a perfect way to get your customers to tell
you what they want and to filter that feedback into
what’s a must-have addition or deletion, what’s possible
to do with a bit of work, and what to ignore.
 By putting a feedback button on the app, you enable the
98
client to tell you what they think would make it better.
By: Zigiju N
Cont…
Updates
Once you have your feedback, you
can sort out how to make your app
more relevant to your customers, and
send out updates periodically.

99

By: Zigiju N
Read more…………

[Link]
service-tutorial

100

By: Zigiju N
thank you

any q?
101

By: Zigiju N
Chapter-4
Android Menus

By: Ins Zigiju N.


May, 2022
Menu
In android, Menu is a part of user
interface (UI) component which is used
to handle some common functionality
around the application.
By using Menus in our applications, we
can provide better and consistent user
experience throughout the application.
Menus are useful for displaying
additional options that are not directly
visible on the main UI of an application.
103

By: Zigiju N
Cont…
In android, to define menu, we need
to create a new folder menu inside of
our project resource directory
(res/menu/) and Description
Element
add a new XML file
to build the menu with the following
<menu> It’s a root element to define a Menu in XML file and it
elements.
will hold one or more elements.

<item> It is used to create a menu item and it represent a


single item in menu. This element may contain a
nested <menu> element in order to create a
submenu.

<group> It’s an optional and invisible for <item> elements. It is 104


used to categorize the menu items so they share
properties such as active state and visibility. By: Zigiju N
Cont…
Following
is the example of defining a menu in XML file
(menu_example.xml).

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


<menu xmlns:android="[Link]
droid">
<item android:id="@+id/inbox"
android:icon="@drawable/ic_inbox"
android:title="@string/inbox" />
<item android:id="@+id/compose"
android:icon="@drawable/ic_compose"
android:title="@string/compose"
android:showAsAction="ifRoom" />
<item android:id="@+id/outbox"
android:icon="@drawable/ic_outbox"
android:title="@string/outbox" />
</menu>
105

By: Zigiju N
Cont…
The <item> element
in menu supports different type of
attributes to define item’s behaviour
and appearance.
Following
Attribute are some of commonly
Description

used <item>
android:id attributes
It is used in element
to uniquely identify android
in
application.
applications.
android:icon It is used to set the item's icon from drawable
folder.

android:title It is used to set the item's title

android:showAsAct It is used to specify how the item should 106


ion appear as an action item in the app bar.
By: Zigiju N
Cont…
 In case if we want to add submenu in menu item, then we
need to add a <menu> element as the child of
an <item>.
 Following is the example of defining a submenu in menu
item.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="[Link]
res/android">
<item android:id="@+id/file"
android:title="@string/file" >
<!-- "file" submenu -->
<menu>
<item android:id="@+id/create_new"
android:title="@string/create_new" />
<item android:id="@+id/open"
android:title="@string/open" /> 107
</menu>
</item> By: Zigiju N
Cont…
 In android, we can handle a menu item click events
using ItemSelected() event based on the menu type.
 Following is the example of handling a context menu item click event
using onContextItemSelected().
@Override
public boolean onContextItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link]:
// do something
return true;
case [Link]:
// do something
return true;
default:
return [Link](item);
}
}
 If you observe above code, the getItemId() method will get the id of
selected menu item based on that we can perform our actions.
108

By: Zigiju N
Types of Android Menu
Android Different Types of Menus
In android, we have a three types of
Menus available to define a set of
options and actions in our android
 Android Options Menu
applications.
 Android Context Menu
The Menus in android applications
Android Popup Menu
are following –

109

By: Zigiju N
Cont…
 Android Options Menu: is a primary collection
of menu items in an android application and
useful for actions that have a global impact on
the searching application.
 Android Context Menu: is a floating menu only
appears when user click for a long time on an
element and useful for elements that effect the
selected content or context frame.
 Android Popup Menu: displays a list of items in
a vertical list which presents to the view that
invoked the menu and useful to provide an
overflow of actions that related to specific
content.
110

By: Zigiju N
Options Menu
In android, Options Menu is a
primary collection of menu items for
an activity and it is useful to
implement actions that have a global
impact on the app, such as Settings,
Search, etc.

111

By: Zigiju N
Cont…
 By using Options Menu, we can combine multiple actions
and other options that are relevant to our current activity
.
 We can define items for the options menu from either
our Activity or Fragment class.
 In case, if we define items for the options menu in both
activity or fragment, then those items will be combined
and display in UI.
Create Android Options Menu in XML File
 In android, to define options menu, we need to create a
new folder menu inside of our project resource directory
(res/menu/) and add a new XML (menu_example) file
to build the menu.
 Following is the example of defining a menu in an XML
file (menu_example.xml). 112

By: Zigiju N
Cont…
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="[Link]
m/apk/res/android">
<item android:id="@+id/mail"
android:icon="@drawable/ic_mail"
android:title="@string/mail" />
<item android:id="@+id/upload"
android:icon="@drawable/ic_upload"
android:title="@string/upload"
android:showAsAction="ifRoom" />
<item android:id="@+id/share"
android:icon="@drawable/ic_share"
android:title="@string/share" />
</menu>
113

By: Zigiju N
Options Menu Example
 Following is the example of implementing
an Options Menu in the android application.
 Create a new android application using android
studio and give names as OptionsMenu. In case
if you are not aware of creating an app in android
studio check this article Android Hello World App.
 In android, to define options menu, we need to
create a new folder menu inside of our project
resource directory (res/menu/) and add a new
XML (options_menu.xml) file to build the menu.
 Now open newly created xml
(options_menu.xml) file and write the code like
as shown below.
114

By: Zigiju N
Cont…
options_menu.xml

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


<menu xmlns:android="[Link]
android" >
<item android:id="@+id/search_item"
android:title="Search" />
<item android:id="@+id/upload_item"
android:title="Upload" />
<item android:id="@+id/copy_item"
android:title="Copy" />
<item android:id="@+id/print_item"
android:title="Print" />
<item android:id="@+id/share_item"
android:title="Share" />
<item android:id="@+id/bookmark_item"
android:title="BookMark" /> 115
</menu>
By: Zigiju N
Cont…
Once we are done with creation of
menu, we need to load this menu XML
resource from our activity
using onCreateOptionsMenu() callb
ack method, for that open main
activity file [Link] from \
java\[Link] path
and write the code like as shown
below.

116

By: Zigiju N
Cont…
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

publicclass MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link].options_menu, menu);
return true;
117
}
By: Zigiju N
Cont…
@Override
public boolean onOptionsItemSelected(MenuItem item) {
[Link](this, "Selected Item: " +[Link](),
Toast.LENGTH_SHORT).show();
switch ([Link]()) {
case [Link].search_item:
// do your code
return true;
case [Link].upload_item:
// do your code
return true;
case [Link].copy_item:
// do your code
return true;
case [Link].print_item:
// do your code
return true;
case [Link].share_item:
// do your code
return true;
case [Link].bookmark_item:
// do your code
return true;
default: 118
return [Link](item);
} }}
By: Zigiju N
Context Menu
In android, Context Menu is like a
floating menu and that appears when the
user performs a long press or click on an
element and it is useful to implement
actions that affect the selected content or
context frame.
 The android Context Menu is more like the
menu which displayed on right-click in
Windows or Linux.
In android, the Context Menu offers
actions that affect a specific item or
context frame in the UI and we can 119

provide a context menu for any view. By: Zigiju N


Context Menu
The context menu won’t support any
item shortcuts and item icons.

120

By: Zigiju N
Context Menu Example
Following is the example of
implementing a Context Menu in
android application.
 Create a new android application using
android studio and give names
as ContextMenuExample.
In case if you are not aware of creating
an app in android studio check this
article Android Hello World App.
Now open an activity_main.xml file
from \res\layout path and write the 121
code like as shown below
By: Zigiju N
Cont…
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
[Link]/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Long press me"
android:layout_marginTop="200dp" android:lay
out_marginLeft="100dp"/> 122
</LinearLayout>
By: Zigiju N
Cont…
Once we are done with the creation
of layout with required control, we
need to load the XML layout resource
from our activity
onCreate() callback method, for
that open main activity
file [Link] from \java\
[Link]
e path and write the code like as
shown below.
123

By: Zigiju N
Cont…
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Button btn = (Button) findViewById([Link]);
registerForContextMenu(btn);
124
}
By: Zigiju N
Cont…
@Override
public void onCreateContextMenu(ContextMenu menu,
View v, [Link] menuInfo) {
[Link](menu, v, menuInfo);
[Link]("Context Menu");
[Link](0, [Link](), 0, "Upload");
[Link](0, [Link](), 0, "Search");
[Link](0, [Link](), 0, "Share");
[Link](0, [Link](), 0, "Bookmark");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
[Link](this, "Selected Item: " +[Link](),
Toast.LENGTH_SHORT).show();
return true;
} 125
}
By: Zigiju N
Popup Menu
In android, Popup Menu displays a
list of items in a modal popup window
that is anchored to the view.
The popup menu will appear below
the view if there is a room or above
the view in case if there is no space
and it will be closed automatically
when we touch outside of the popup.
The android Popup Menu provides an
overflow style menu for actions that
126
are related to specific content.
By: Zigiju N
Cont…
 In android, the Popup Menu provides an
overflow of actions that are related to
specific content and the actions in the
popup menu won’t affect the corresponding
content.
 The popup menu won’t support any item
shortcuts and item icons.
 In android, the Popup menu is available with
API level 11 (Android 3.0) and higher
versions.
 If you are using Android 3.0 +, the Popup
Menu won’t support any item shortcuts and 127
item icons in the menu.
By: Zigiju N
Popup Menu Example
Following is the example of
implementing a Popup Menu in the
android application.
 Create a new android application using
android studio and give names
as PopupMenuExample.
In case if you are not aware of creating
an app in android studio check this
article Android Hello World App.
Now open an activity_main.xml file
from \res\layout path and write the 128
code like as shown below
By: Zigiju N
Cont…
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
[Link]/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Menu"
android:layout_marginTop="200dp" android:layo
ut_marginLeft="100dp"/> 129
</LinearLayout>
By: Zigiju N
Cont…
In android, to define the popup
menu, we need to create a new
folder menu inside of our project
resource directory (res/menu/) and
add a new XML (popup_menu.xml)
file to build the menu.
 Now open newly created xml
(popup_menu.xml) file and write
the code like as shown below.

130

By: Zigiju N
Cont…
popup_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="[Link]
apk/res/android" >
<item android:id="@+id/search_item"
android:title="Search" />
<item android:id="@+id/upload_item"
android:title="Upload" />
<item android:id="@+id/copy_item"
android:title="Copy" />
<item android:id="@+id/print_item"
android:title="Print" />
<item android:id="@+id/share_item"
android:title="Share" />
<item android:id="@+id/bookmark_item"
android:title="BookMark" /> 131
</menu>
By: Zigiju N
Cont…
Once we are done with the creation
of the menu, we need to load this
menu XML resource from our activity
by instantiating
a Popup constructor, for that open
main activity
file [Link] from \java\
[Link]
path and write the code like as shown
below.
132

By: Zigiju N
Cont…
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public
class MainActivity extends AppCompatActivity implements PopupM
[Link] {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
Button btn = (Button) findViewById([Link]);
[Link](new [Link]() { 133
@Override
By: Zigiju N
Cont…

public void onClick(View v) {
PopupMenu popup
= new PopupMenu([Link], v);

[Link](MainActi
[Link]);

[Link]([Link].popup_menu);
[Link]();
}
});
} 134

By: Zigiju N
Cont…
 @Override
public boolean onMenuItemClick(MenuItem item) {
[Link](this, "Selected Item: " +[Link](), Toast.LENGTH_SHORT).show();
switch ([Link]()) {
case [Link].search_item:
// do your code
return true;
case [Link].upload_item:
// do your code
return true;
case [Link].copy_item:
// do your code
return true;
case [Link].print_item:
// do your code
return true;
case [Link].share_item:
// do your code
return true;
case [Link].bookmark_item:
// do your code
return true;
default:
return false;
}
} 135
}
By: Zigiju N
thank you

any q?
136

By: Zigiju N
Chapter-5
Android Data Storage

By: Ins Zigiju N.


May, 2022
Shared Preferences
 Shared Preferences are used to save and retrieve
the primitive data types (integer, float, Boolean, string,
long) data in the form of key-value pair from a file
within an apps file structure.
 The Shared Preferences object will point to a file
that contains a key-value pairs and provides a simple
read and write methods to save and retrieve the key-
value pairs from a file.
 The Shared Preferences file is managed by an android
framework and it can be accessed anywhere within the
app to read or write data into the file, but it’s not
possible to access the file from any other app so it’s
secured.
 The Shared Preferences are useful to store the small
collection of key-values such as user’s login
information, app preferences related to users, etc. to138
maintain the state of app, next time when they login
By: Zigiju N
Handle a Shared Preferences
In android, we can save the preferences
data either in single or multiple files
based on our requirements.
In case if we use single file to save the
preferences, then we need to
use getPreferences() method to get
the values from Shared Preferences file
and for multiple files we need to call
a getSharedPreferences() method
and pass a file name as a parameter.
139

By: Zigiju N
Cont…
Method Description

getPreferences() This method is for activity level preferences


and each activity will have it's own
preference file and by default this method
retrieves a default shared preference file
that belongs to the activity.

getSharedPrefere This method is useful to get the values from


nces() multiple shared preference files by passing
the name as parameter to identify the file.
We can call this from any Context in our app.

140

By: Zigiju N
Cont…
If we are using single shared
preference file for our activity, then
we need to initialize
the SharedPreferences object by
using getPreferences() method
like as shown below.
SharedPreferences sharedPref =
getPreferences(Context.MODE_PRI
VATE);

In case, if we are using multiple141


shared preference files, then By:we
Zigiju N
Write to Shared Preferences
To store a data in shared preference
file, we need an editor to edit and
save the changes
in SharedPreferences object.
SharedPreferences
Following sharedPref
is the = code snippet to
store the data in shared preference
getPreferences(Context.MODE_PRIVATE);
[Link] editor = [Link]();
file using editor.
[Link]("keyname",true);

[Link]("keyname","string value");
[Link]("keyname","int value");

[Link]("keyname","float value");
142
[Link]("keyname","long value");

[Link](); By: Zigiju N


Read from Shared Preferences
To read or retrieve a values from
Shared Preferences file, we need to
call a methods such
as getInt(),
SharedPreferences prefgetString(),
= etc. by
providing the key for the value which
getPreferences(Context.MODE_PRIVATE);
[Link]("keyname",null);
we want to get like as shown below.
[Link]("keyname",0);
[Link]("keyname",0);
[Link]("keyname",true);
[Link]("keyname",0);

143

By: Zigiju N
Deleting from Shared Preferences
To delete a value from Shared
Preferences file, we need to call
a remove() method by providing the
key for theprefvalue
SharedPreferences = which we want to
getPreferences(Context.MODE_PRIVATE);
delete like as shown
[Link] below.
editor = [Link]();
[Link]("keyname");
[Link]();

Clearing from Shared Preferences


SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
[Link] editor = [Link]();
We can clear all the data from
[Link]();
[Link](); 144
Shared Preferences file
By: Zigiju N
Android Session Management
In android, Session
Management is a process which is
used to maintain the required
values in a session to use it in
application.
In android we can manage the
logged in user details in session
either by storing it in global variables
or in Shared Preferences.
In case, if we store the values in
global variables, those will be lost145
whenever the user closes By:the Zigiju N
Internal Storage
 In android, Internal Storage is useful to
store the data files locally on the
device’s internal memory
using FileOutputStream object.
After storing the data files in device
internal storage, we can read the
data file from device
using FileInputStream object.
 The data files saved in internal
storage is managed by an android
framework and it can be accessed146
anywhere within the app to read or N
By: Zigiju
Cont…
Write a File to Internal Storage
By using
android FileOutputStream object a
nd openFileOutput method, we can
easily create and write a data to a
file in device’s internal storage.
Following is the code snippet to
create and write a private file to the
device
String internal
FILENAME memory.
= "user_details";
String name = "abebe";
 We used
FileOutputStream write()
fstream method to
= openFileOutput(FILENAME, write
Contex-
t.MODE_PRIVATE);
the data
[Link]([Link]()); in file and147
[Link]();
used close() method to close By:the Zigiju N
Cont…
Read a File from Internal Storage
By using
android FileInputStream object an
d openFileInput method, we can
easily read the file from device’s
internal storage.
String FILENAME = "user_details";
FileInputStream fstream = openFileInput(FILENAME);
 StringBuffer
Following is= new
sbuffer theStringBuffer();
code snippet to
int i;
read [Link]())!=
while ((i = data from-1){file which is in
device’s
}
internal
[Link]((char)i); memory.
[Link]();
148

By: Zigiju N
External Storage
 In android, External Storage is useful to
store the data files publicly on the
shared external storage
using FileOutputStream object.
After storing the data files on
external storage, we can read the
data file from external storage media
using FileInputStream object.
The data files saved in external
storage are word-readable and can
be modified by the user when they149
enable USB mass storage to transfer By: Zigiju N
Cont…
Grant Access to External Storage
To read or write files on the external
storage, our app must be acquire
the two permissions
WRITE_EXTERNAL_STORAGE and R
EAD_EXTERNAL_STORAGE system
<manifest>
permissions.
....
<uses-
permission
For that, we need to add following
android:name="[Link].WRITE_EXTERN
AL_STORAGE"/>
permissions
<uses- in android manifest file
like as shown below.
permission android:name="[Link].READ_EXTERN
AL_STORAGE"/>
.... 150
</manifest>
By: Zigiju N
Cont…
Write a File to External Storage
By using
android FileOutputStream object
and getExternalStoragePublicDir
ectory method, we can easily create
and write a data to the file in
String FILENAME = "user_details";
external
String storage public folders.
name = "abebe";

FileFollowing
folder = is the code snippet to
[Link](Environment.
create and write a public file in
DIRECTORY_DOWNLOADS);
File myFile = new File(folder, FILENAME);
device Downloads
FileOutputStream folder.
fstream = new FileOutputStream(myFile);
[Link]([Link]()); 151
[Link]();
By: Zigiju N
Cont…
Read a File from External Storage
By using
android FileInputStream object
and getExternalStoragePublicDir
ectory method, we can easily read
String FILENAME = "user_details";
the
File file
folder = from external storage.
[Link](Environment.
 Following is the code snippet to
DIRECTORY_DOWNLOADS);
File myFile = new File(folder, FILENAME);
read a fstream
FileInputStream data = newfrom file which is
FileInputStream(myFile);
in downloads folder.
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = [Link]())!= -1){
[Link]((char)i);
} 152
[Link]();
By: Zigiju N
SQLite
SQLite is an open source light weight
relational database management
system (RDBMS) used to perform
database operations, such as
storing, updating, retrieving data
from database.
In our android applications Shared
Preferences, Internal
Storage and External
Storage options are useful to store
and maintain the small amount of153
data. By: Zigiju N
Cont…
By default, Android comes with built-
in SQLite Database support so we
don’t need to do any configurations.
Just like we save the files on
device’s internal storage, Android
stores our database in a private disk
space that’s associated to our
application and the data is secure,
because by default this area is not
accessible to other applications.
The 154

package [Link] By: Zigiju N


Cont…
Create Database and Tables using
SQLite Helper
In android, by
using SQLiteOpenHelper class we
can easily create required database
and tables for our application.
To use SQLiteOpenHelper, we
need to create a subclass that
overrides
the onCreate() and onUpgrade() c
all-back methods. 155

Following is the code snippet of By: Zigiju N


Cont…
public
class DbHandler extends SQLiteOpen
Helper {
private static final
int DB_VERSION = 1;
private static
final String DB_NAME = "usersdb";
private static
final String TABLE_Users = "userdeta
ils";
private static 156
final String KEY_ID = "id"; By: Zigiju N
Cont…
@Override
public
void onCreate(SQLiteDatabase db){
String CREATE_TABLE = "CREATE
TABLE " + TABLE_Users + "("
+ KEY_ID + " INTEGER PRI-
MARY KEY
AUTOINCREMENT," + KEY_NAME + "
TEXT,"
+ KEY_LOC + " TEXT,"
+ KEY_DESG + " TEXT"+ ")";157
[Link](CREATE_TABLE); By: Zigiju N
Cont…
@Override
public
void onUpgrade(SQLiteDatabase
db, int oldVersion, int newVersion){
// Drop older table if exist
[Link]("DROP TABLE IF EX-
ISTS " + TABLE_Users);
// Create tables again
onCreate(db);
}
} 158

By: Zigiju N
Cont…
If you observe above code, we are
creating database “usersdb” and
table “userdetails”
using SQLiteOpenHelper
Method Description
class by
overriding
onCreate()
onCreate and onUpgrad
This method is called only once throughout the
e methods.
application after database is created and the table
creation statements can be written in this method.

onUpgrade() This method is called whenever there is an updation in


database like modifying the table structure, adding
constraints to database, etc.

159

By: Zigiju N
Cont…
Insert Data into SQLite Database
In android, we can insert data into
SQLite database by
passing ContentValues to insert()
method.
//Get the Data Repository in write mode
SQLiteDatabase
The following db = [Link]();
//Create a new map of values,code snippet
where column shows
names are the keys
how to cValues
ContentValues insert = newdata into SQLite
ContentValues();
[Link](KEY_NAME, name);
database using
[Link](KEY_LOC, insert() method.
location);
[Link](KEY_DESG, designation);
// Insert the new row, returning the primary key value of the new
row
long newRowId = [Link](TABLE_Users,null, cValues); 160

By: Zigiju N
Cont…
Read the Data from SQLite
Database
In android, we can read the data
from SQLite database
using query()
//Get the Data method.
Repository The following
in write mode
SQLiteDatabase db = [Link]();
code snippet
Cursor cursor shows how new
= [Link](TABLE_Users, to String[]{
read the
data from SQLite
KEY_NAME, KEY_LOC, KEY_DESG
},
Database
using query()
KEY_ID+ "=?",new method.
String[]{
[Link](userid)
}
,null, null, null, null);

161

By: Zigiju N
Cont…
Update Data in SQLite Database
In android, we can update the data
in SQLite database
using update() method in android
applications. The following code
//Get the Data Repository in write mode
snippet shows
SQLiteDatabase how to update the
db = [Link]();
data
ContentValues in SQLite
cVals = new ContentValues();database
[Link](KEY_LOC, location);
using update()
[Link](KEY_DESG, method.
designation);
int count = [Link](TABLE_Users, cVals, KEY_ID+" =
?",
new String[]{
[Link](id)
}); 162

By: Zigiju N
Cont…
Delete Data from SQLite Database
In android, we can delete data from
SQLite database
using delete() method.
//Get
The the Data Repository in write mode
following code snippet shows
SQLiteDatabase db = [Link]();
how to delete KEY_ID+"
[Link](TABLE_Users, the data = ?", from SQLite
new String[]{
database using delete() method.
[Link](userid)
});

163

By: Zigiju N
Web Service with PHP/Java & MySQL
External Databases are also the data
repository for android apps for
example apps that provide weather
information, exchange rates, world
news etc.
 Web Services
MySQL
 JDBC is one of theweb
database tool.
without
Connection
services between an android app
and mysql can be done through:

164
A web service is a standard used for
By: Zigiju N
Cont…
Web Services expect the computer
network to support standard Web
protocols such as XML, HTTP, HTTPS,
FTP, and SMTP.
Expose method as a service over network
Here are the
Application reasons for using Web
Inter-operability
 Connect heterogeneous applications

Service:
Standardized protocol
 Cost effective communication

 Make client more lightweight


 Re-usage of existing functionalities
 Remote DB hit made simple 165
Here are the few advantages of By: Zigiju N
Cont…
Web Service Architecture
An ideal Webservice provider is
designed around four logical layers
which define the ways in which data
is to be transported, encoded,
exposed and discovered by the
users.

166

By: Zigiju N
Cont…
There are two widely used forms of
invoking and consuming Web
Services:
Representational State Transfer
(REST)
Closely tie to the HTTP protocol by
associating its operation to the
common methods: GET, POST, PUT,
DELETE for HTTP/HTTPS.
This model has a simple invocation
mode and little overhead. 167

Service calls rely on a URL which


By: Zigiju N
Cont…
Remote Procedure Call (RPC).
Remote services are seen as
coherent collections of discoverable
functions (or method calls) stored
and exposed by EndPoint providers.
Some implementations of this
category include: Simple Object
Access Protocol (SOAP), Common
Object Request Broker Architecture
(CORBA), Microsoft's Distributed
Component Object Model (DCOM)168
and Sun Microsystems's Java/Remote
By: Zigiju N
Cont…
REST vs. SOAP
Although SOAP and REST
technologies accomplish the same
final goal, that is request and receive
a service, there are various
differences between them.
REST users refer to their remote
services through a conventional URL
that commonly includes the location
of the (stateless ) server, the service
name, the function to be executed169
and the parameters needed by the
By: Zigiju N
Cont…
SOAP accepts a variety of transport
mechanisms, among them HTTP,
HTTPS, FTP, SMTP, etc. SOAP uses
WSDL (Web Service Description
Language) for exposing the format
and operation of the services. REST
lacks an equivalent exploratory tool.

170

By: Zigiju N
thank you

any q?
171

By: Zigiju N

You might also like