2. Getting Started with Android
Target-1
A little background of Mobile application development
Introduction to Android
Android Architecture
Android and Linux Kernel
Android Software Stack
Android Activities and Libraries
Dalvik Virtual Machine
Android Development Environment
Android emulator
Hello world Program
AndroidWallet.blogspot.in
3. Mobile application development
The previous Mobile generations
1979–1992 Mobiles Phones have Embedded System to control
operation.
1993 The first Smartphone, the IBM Simon, has a touch
screen, email and PDA features.
From 1995 to 2005 revolution came in mobile platforms.
Used proprietary low and middle wares
Focused mainly on Communications
Some phones had some additional features like
Music Players, Camera, Locations etc.
There was no much focus on the other uses of the
mobile platform
No focus on developers
No rich framework
AndroidWallet.blogspot.in
4. Mobile application development
Mobile generations….
Symbian was created to provide developers a wider
target audience
Enabling the developers to build rich applications and
leverage the hardware better
But coding has to be done in C/C++ using the
proprietary APIs
Portability became the key issue
AndroidWallet.blogspot.in
5. Mobile application development
Phone Characteristics (1995-2005)
Low memory
Low processing power
Different types of displays like
Text, LCD, etc.,
Response to communication was the most important
task.
Different keyboard layouts
Security of Application and Data
Location based approach
Support for Java and J2ME
AndroidWallet.blogspot.in
6. Mobile application development
Support for Java through J2ME
Midlets running on Light Weight VM
Supported only a subset of the actual framework
J2ME supported only simple apps
Supported portability
Lesser access to the underlying hardware
Focused more on game development
Has access to
• Smaller Screens
• Simple numerical keypads
• Limited access to HTTP
AndroidWallet.blogspot.in
7. Mobile application development
New Revolution in Mobile field started.
Touch based mobile came.
• Windows Mobile
Email based mobile introduced by Blackberry.
AndroidWallet.blogspot.in
8. Mobile application development
Phone started with multi-functionality.
Called “Smart Phone”.
Gestures based UI (multi touch)
iPhone was introduced and provided rich framework
•Used objective C for development
Apps were developed and pushed to the stores
•Either free and commercial ones.
AndroidWallet.blogspot.in
9. Smart Phones: Platform 2008 [Android]
Platform for Smart Phones
Developed by Android Inc. later taken over by Google.
Andy Rubin is the father of Android.
It is a platform based on Linux kernel.
Its an open source.
Has a lean, powerful middleware based on DV machine.
Optimized, easy to deliver application framework using java.
Has a rich market place.
Libraries written in C includes
Surface manager, Open Core media framework, SQLite
relational database management system, OpenGL ES 2.0 3D
graphics API, Web-Kit layout engine, SGL graphics engine, SSl,
Bionic libc.
AndroidWallet.blogspot.in
10. Android: How does it help?
For Device Manufacturers
Focus on hardware and user interface innovations.
Get basic applications automatically
Get ready for app markets
Get access to fast changing innovation in mobile software
Platforms
• Desktop class internet browsing
• Location based applications
• Multimedia support and Multitasking
They can still have unique locks
AndroidWallet.blogspot.in
11. Android Architecture
For application / software owners
Develop software / application for new mobiles
New sales and distribution channel
Track sales / revenue
Feature richness
More complex application can be made eisaly
New areas to explore
AndroidWallet.blogspot.in
12. Architecture The Kernel Layer
For Application & System Developers
Create new applications quickly using Java
Reuse other applications in a new unique manner
Hides several complexities of development, debugging,
testing,
deploying apps on mobile devices
System Developers
New structure upon kernel
Can build additional SDK (Add ons)
Open code base
AndroidWallet.blogspot.in
13. Android: How does it help?
For Google / Android
Play in the fast growing mobile industry
Create new advertising space
Diversify into consumer electronics
AndroidWallet.blogspot.in
14. Android: open Handset Alliance(OHA)
A business alliance consisting of 47 companies to develop
open standards for mobile devices.
AndroidWallet.blogspot.in
15. Android: open Handset Alliance(OHA)
different versions as of June 3, 2013.
AndroidWallet.blogspot.in
16. Android: open Handset Alliance(OHA)
Choosing an API level
1-Current Distribution
2-Choosing a lower API level may support more devices
but gain less functionality for your app.
Android 1.5 - 2.3 (API levels 3-10) - Android made
specifically for smartphones.
Android 3.0 - 3.2 (API levels 11-13) - Honeycomb, Android
made for tablets.
Android 4 (API levels 14-) - Ice Cream Sandwich - Current
generation,for both phone and tablets.
AndroidWallet.blogspot.in
17. Android Architecture
Basics
A Software stack for mobile devices developed and
managed by OHA.
A free Software under Apache License.
AndroidWallet.blogspot.in
19. Architecture The Kernel Layer
The Kernel Layer
Relying on Linux Kernel 2.6 for core system services
• Memory and Process Management
• Network Stack
• Driver Model
• Security
Providing an abstraction layer between the H/W and the
rest of the S/W stack
AndroidWallet.blogspot.in
20. Architecture The Kernel Layer
The Kernel Enhancements
Alarm
Ashmem
Binder
Power Management
Low Memory Killer
Kernel Debugger
Logger
AndroidWallet.blogspot.in
21. Architecture The Kernel Layer
Binder
Driver to facilitate IPC between applications and
services
Problems of Linux IPC
• Applications and Services may run in separate
processes but must communicate and share data
• IPC can introduce significant processing overhead
and security hole
Properties of Binder
• High performance through shared memory
• Per-process thread pool for processing requests
• Reference counting and mapping of object
references across processes
• Synchronous calls between processes
AndroidWallet.blogspot.in
22. Architecture The Kernel Layer
Binder in Action
A pool of threads is associated to each service
application to process incoming IPC.
Binder performs mapping of object between two
processes.
Binder uses an object reference as an address in a
process’s memory space.
AndroidWallet.blogspot.in
23. Architecture The Kernel Layer
Power Management
Problem
• Mobile devices depend on battery power and
batteries have limited capacity.
Properties of Power Management
• PM is built on top of standard Linux Power
Management.
• PM supports more aggressive power management
policy.
• Components make requests to keep the power on
through “Wake Locks”.
• PM supports several different types of wake “Wake
Locks”.
AndroidWallet.blogspot.in
24. Architecture The Kernel Layer
Power Management in action (conti..)
Four types of WAKELOCKS present in power manager.
•
•
•
•
PARTIAL_WAKE_lOCK
SCREEN_DIM_WAKE_lOCK
SCREEN_BRIGHT_WAKE_LOCK
FULL_WAKE_LOCK
AndroidWallet.blogspot.in
25. Architecture The Kernel Layer
Power Management in action
If there are no
active wake locks,
CPU will be
turned off.
If there are no
partial wake locks,
screen and
keyboard will be
turned off
AndroidWallet.blogspot.in
26. Architecture The Libraries
Running on top of the Linux kernel, android provides
various C/C++ core libraries that include
• Media library (audio & Video)
• Surface manager for display
• Graphics libraries that include SGL and OpenGL
• SQLite for native database support
• SSL and Web-Kit for web browsing and internet
security
AndroidWallet.blogspot.in
27. Architecture The Android Runtime
Libraries & VM
Android runtime is the engine that powers the android.
Includes the Dalvik Virtual Machine and Core Libraries
app.
Android app development is done in Java, but Dalvik VM is
not a JVM.
Java .class files don’t run in android, instead they have to
be converted into .dex files
AndroidWallet.blogspot.in
28. Architecture The Android App Framework
Provides the classes used to create android application.
Also provides generic access to hardware resources
manages user interface and application resources.
Package Manager manages the installation of the
application
AndroidWallet.blogspot.in
29. Architecture The Application Layer
All native and third party applications (including the
developers’ apps.
The application layer runs within the Android Runtime
using the classes and services made available from the
application framework.
Some of the built-in application: Dialer, Messaging,
Contacts, Camera, Maps etc.
Launcher looks for the activity marked with
category.LAUNCHER and starts the activity.
AndroidWallet.blogspot.in
31. Application Dependency
Dalvik Virtual Machine
Since the development language of Android application is
Java. Need a Java virtual machine for running application.
Compiles java code to Dalvik Executable(dex format).
It is a register based virtual machine for efficient execution,
not stack based in traditional java.
AndroidWallet.blogspot.in
32. Android: Development Kit
Android offers two development kits
SDK (Software Development Kit)
• Used for App development in Java
• Can be used / developed in Mac, Windows XP or Linux
NDK (Native Development Kit)
• For native code development using C/C++
• Needs Linux or Linux shell (Cygwin)
AndroidWallet.blogspot.in
34. Types of Application Artifacts
A typical android app consists one or more activities.
An activity is roughly equivalent to a Windows-form .
An activity usually shows a single visual user interface(UI).
Only one activity is chosen to be executed first when an
application is launched.
An activity may transfer control or data to another activity
through an inter process communication protocol called
intents.
AndroidWallet.blogspot.in
35. Types of Application Artifacts
Services are special type of activity that do not have a visual
user interface.
Services usually run in the background for an independent
period of time.
Applications start their own services or connect to services
already active.
Example…
AndroidWallet.blogspot.in
36. Types of Application Artifacts
A Broadcast Receiver is a dedicated listener that waits for
system-wide or locally transmitted messages.
Broadcast Receivers do not display a user interface.
They typically register with system by the means of a filter
acting like a key. When the broadcast message matches the
key the receiver is activated.
A Broadcast Receiver could respond by either executing a
specific activity or use the notification mechanism to request
the user’s attention.
AndroidWallet.blogspot.in
37. Types of Application Artifacts
A Content provider is a data-centric service that makes
persistent datasets available to any number of applications.
Common global datasets include: contacts, pictures, messages,
audio files, emails.
The global datasets are usually stored in SQLite database.
The Content Provider class offers a standard set of “database”
like methods to enable other apps to retrieve, delete, update
and insert data items.
AndroidWallet.blogspot.in
40. Development Environment
For Application development
Windows XP / Vista / 7 or Mac or Linux
Java 6.0 SDK
Eclipse Helios or Indigo or Juno
Eclipse ADT plugin
Android SDK
AndroidWallet.blogspot.in
41. Eclipse
Introduction
Plugins for Eclipse
• Installation
• ADT Plugin
features for development
• Project, Classes, Manifest, Layout, XML
• Build, Debug, Deploy
AndroidWallet.blogspot.in
43. Emulator
How to create?
Once we have
downloaded the various
platform tool, we have to
create AVD.
Double click on “AVD
manager” from SDK folder
Click “new ” button to
create a virtual device.
Fill the text boxes as
showed and click on
create AVD.
AndroidWallet.blogspot.in
44. Emulator
Functions
Several things can be
simulated
• Send / Receive
SMS Receive calls
• Locations
• Send touch events
• Set virtual phone
settings like
battery status, AC
charging, etc
AndroidWallet.blogspot.in
45. Question 1Question 2-
Make a POC for display your name on Activity?
Make a POC for display your details like Name, Dob,
Address on Activity?
AndroidWallet.blogspot.in
47. Activity: States
Different States of Activity
Active (Foreground and fully visible)
Paused (Partially Visible)
Stopped (Not Visible)
Removed / Killed
onCreate(Bundle) saving and restoring state
AndroidWallet.blogspot.in
48. Process: Lifecycle
Foreground Process
These processes are assigned
the highest level of priority.
At any one time there are
unlikely to be more than one or
two foreground process active
and these are usually the last to
be terminated by the system.
•Hosts a Broadcast Receiver
that is currently executing its
onReceive() method.
AndroidWallet.blogspot.in
49. Process: Lifecycle
Visible Process
An activity that is visible to the user but not in the
foreground, such as one sitting behind a foreground
dialog) is considered extremely important and will not be
killed unless that is required to keep the foreground
activity running.
Service Process
Processes that contain a Service that has already been
started and is currently executing.
AndroidWallet.blogspot.in
50. Process: Lifecycle
Background Process
an activity that is not visible to the user and has been
paused.
Empty Process
Empty processes no longer contain any active
applications and are held in memory ready to serve as
hosts for newly launched applications.
Such processes are, obviously, considered to be the
lowest priority and are the first to be killed to free up
resources.
These are killed very quickly by the system as memory
becomes low.
AndroidWallet.blogspot.in
51. Manifest
Attributes
xmlns ; the name of the namespace (android) and
where the DTD for the xml parser is located
package ; the name of the java package for this
application (must have at least two levels)
android:version ; the version code for this version of the
app
android:versionName ; The version name (for
publishing)
AndroidWallet.blogspot.in
53. Intent
what’s an intent?
Child tag of <activity>
an intent is a message sent from one program to another
(message dispatcher) to tell the system what to do next.
Typically an intent consists of two parts; an action and the
data that that action is supposed to use to do it.
When you select an icon on the main page the intent is to
run the app associated with that icon
The tag is used to construct an android.content.IntentFilter
object to handle a particular android.content.Intent
AndroidWallet.blogspot.in
54. Intent
Fundamentally an Intent is a message
That activates activity, service and broadcast receivers
Launch an Activity or a Service
Broadcast an Event
Asking for content from CP
Activity-1
Intent
Activity-2
Activity-3
AndroidWallet.blogspot.in
55. Intent
Types of Intent
Explicit Intent
Implicit Intent
Explicit intents explicitly defines the component which
should be called by the Android system, by using the Java
class as identifier.
Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);
AndroidWallet.blogspot.in
56. Intent
Types of Intent (Cont….)
Implicit intents specify the action which should be
performed and optionally data which provides data for
the action.
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(intent);
AndroidWallet.blogspot.in
57. Intent
Standard available categories
android.intent.category.DEFAULT
android.intent.category.LAUNCHER
android.intent.category.HOME
AndroidWallet.blogspot.in
58. Question 1Question 2-
Make a POC for switching from one Activity to other
Activity?
Make a POC for sending your Name, Dob from one
Activity to other Activity?
AndroidWallet.blogspot.in
60. Android Widgets
Basics
Widgets are little applications which can be placed on a
widget host, typically the home screen or the lock screen, of
your Android device.
A widget runs as part of the process of its host. This requires
that widgets preserve the permissions of their application.
AndroidWallet.blogspot.in
61. Android Widgets
Toast
A toast is a widget that displays some information on the
screen and doesn’t steel away the input focus.
A toast can be launched from any component
A toast is automatically dismissed
A toast is asynchronous.
android.widget.Toast is the class used to display them
Toast tst = Toast.makeText(context, message,Duration);
tst.show();
AndroidWallet.blogspot.in
62. Resource (res) Directory Layout
The res directory has the following layout
Animation and Drawable Resources
• res/anim R.anim
• res/drawable R.drawable
Color State Resources
• res/color R.color
Layout Resources
• res/layout R.layout
Menu Resources
• res/menu R.menu
String Resources
• res/values R.string, R.array
Style Resouces
• res/style R.style
AndroidWallet.blogspot.in
63. Resources The “R” class
Referring to resources from code
<your.package>.R.java class gets generated whenever the
project gets built.
• This class provides quick access to all resources
• Layouts, widgets within the resources
• Raw data that needs to be packaged
• Localizable string
com.android.R class provides the shareable resources
offered by the android platform
R.color.red
R.string.titlevalue
AndroidWallet.blogspot.in
64. Basic of Android UI Design
Views
Are the base class for all UI elements (controls or widgets)
All UI controls (including the layout classes) derive from
View
Controller
View
Model
AndroidWallet.blogspot.in
65. Android UI Design
Widget Toolbox
Android supplies with a standard set of views to create
simple interfaces
Some of the widgets:
•TextView
•EditText
•Button
•Spinner
•ListView
•CheckBox
AndroidWallet.blogspot.in
66. Android UI Design
Layout Managers
Layout is the architecture for the user interface in an
activity.
It defines the layout structure and holds all the elements
that appear to the user
Layout managers are extensions of view group used to
position controls (widgets) for your UI
Layouts can be nested allowing you to create complex UI
Some of the layouts
•FrameLayout
•LinearLayout
•RelativeLayout
•TableLayout
AndroidWallet.blogspot.in
67. Android UI Design
Layout Managers (Conti….)
Layouts can be created either using XML or
programmatically (xml being the preferred way). It defines
the layout structure and holds all the elements that appear
to the user.
Views use the constants wrap_content and
fill_parentrather than exact height or width in pixels
These constants are simple and more powerful ensuring
that the layouts are screen size & resolution independent
The wrap_content will set with minimium size required to
fill the content.
The fill_parent expands the view to the full size of the
parent.
AndroidWallet.blogspot.in
68. Examples of Layout
Android Layout
An Android layout is a class that handles arranging the way
its children appear on the screen. Anything that is a View
can be a child of a layout.
The standard layouts are,
• Linear
• Absolute
• Relative
• Frame
• Table
AndroidWallet.blogspot.in
69. Examples of Layout
Absolute Layout
Absolute Layout is based on the simple idea of placing each
control at an absolute position.
Specify the exact x and y coordinates on the screen for
each control
It was used rarely because it makes inflexibilities so
very risk to maintain
AndroidWallet.blogspot.in
71. Examples of Layout
Frame Layout
Frame Layout is designed to display a single item at a time
You can have multiple elements within a Frame Layout but
each element will be positioned based on the top left of the
screen.
Frame Layout 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.
AndroidWallet.blogspot.in
73. Examples of Layout
Linear Layout
Linear Layout organizes elements along a single line.
You specify whether that line is vertical or horizontal
using android:orientation.
Here is a sample Layout XML using Linear Layout.
AndroidWallet.blogspot.in
75. Examples of Layout
Relative Layout
Relative Layout 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.
Relative To Other Elements
• android:layout_above – Places the element above the specified
element
• android:layout_below – Places the element below the specified
element
• android:layout_toLeftOf – Places the element to the left of the
specified element
• android:layout_toRightOf – Places the element to the right of the
specified element
AndroidWallet.blogspot.in
76. Examples of Layout
Relative To Container
These properties will layout elements relative to the parent
container:
android:layout_alignParentBottom – Places the bottom of the
element on the bottom of the container
android:layout_alignParentLeft – Places the left of the element on
the left side of the container
android:layout_alignParentRight – Places the right of the element
on the right side of the container
android:layout_alignParentTop – Places the element at the top of
the container
android:layout_centerHorizontal – Centers the element horizontally
within its parent container
android:layout_centerInParent – Centers the element both
horizontally and vertically within its container
android:layout_centerVertical – Centers the element vertically
within its parent container
AndroidWallet.blogspot.in
77. Examples of Layout
Alignment With Other Elements
android:layout_alignBaseline – Aligns baseline of the new element with
the baseline of the specified element
android:layout_alignBottom – Aligns the bottom of new element in
with the bottom of the specified element
android:layout_alignLeft – Aligns left edge of the new element with the
left edge of the specified element
android:layout_alignRight – Aligns right edge of the new element with
the right edge of the specified element
android:layout_alignTop – Places top of the new element in alignment
with the top of the specified element
AndroidWallet.blogspot.in
79. Examples of Layout
Table Layout
Table Layout organizes content into rows and columns. The
rows are defined in the layout XML, and the columns are
determined automatically by Android. This is done by
creating at least one column for each element.
You can specify that an element should occupy more than
one column using android:layout_span. This can increase
the total column count as well, so if we have a row with two
elements and each element has android:layout_span=”3″
then you will have at least six columns in your table.
AndroidWallet.blogspot.in
81. Optimizing Layouts
Tips
Inflating layout in activities is an expensive process
Each additional nested layouts can have dramatic
influence on performance
Some of the guidelines
Avoid unnecessary nesting
Avoid too many views (not more than 80 views)
Avoid deep nesting (not more than 10 levels)
AndroidWallet.blogspot.in
82. ListView
Basics
Listview is a view group that creates a list of scrollable
items.
These items are automatically inserted into the list using
ListAdapter.
The ListAdapter is a bridge between the Listview and the
data that backs the list.
The data may come from an array or a cursor or virtually
any data source.
Listview can display any data that is wrapped in a
ListAdapter.
AndroidWallet.blogspot.in
83. Custom ListView [Base Adapter]
Basics
A scrollable list of places= Tutorial
Create a new android project Layouts Demo
Create a layout named listitem.xml with the content as y
shown.
Open the created .java file and change the base class from
Activity to ListActivity.
Add the onCreate() method as displayed
Tip: Use android.R.layout.simple_list_item_1instead of
creating a separate listitem.xml
AndroidWallet.blogspot.in
84. BaseAdapter
Basics
BaseAdapteracts as the base for all the adapter
implementations.
ArrayAdapter<T> is one such example.
Some of the common members that must be
implemented by any adapter implementation are
• getCount()
• getItem()
• getItemId() –returns the unique id of the item (primary
key)
• getView() –bad, good, better ways
A demo of custom adapter
AndroidWallet.blogspot.in
85. Question 1Question 2-
Make a POC for listview.
Make a POC for Custom listview.
AndroidWallet.blogspot.in
88. Android Graphics
OpenGL Introduction
Android graphics are powered by
• A custom 2D graphics library
• OpenGL ES 1.0 for higher performance 3D graphics
• The most common 2D graphics API’s can be found in
the drawable package.
OpenGL API’s are available from the Khronos OpenGL ES
package, plus some android OpenGL utilities.
AndroidWallet.blogspot.in
89. Android Graphics
What is Drawable
A Drawable is a general abstraction for something that can
be drawn.
Drawablw class extends to define a variety of specific
kinds of drawable graphics, including
BitmapDrawable
Shapedrawable
PictureDrawable
LayoutDrawable etc..
You can also extends these to define your own custom
Drawable objects that behave in unique ways.
AndroidWallet.blogspot.in
90. Android Graphics
BitmapDrawable
A Drawable that wraps a bitmap and can be tiled,
stretched, or aligned.
You can create a BitmapDrawable from a file path, an
input stream, through XML inflation, or from
a Bitmap object.
• android:gravity
• android:src
AndroidWallet.blogspot.in
91. Android Graphics
Shapedrawable
A Drawable object that draws primitive shapes.
A ShapeDrawable takes a Shape object and manages its
presence on the screen.
If no Shape is given, then the ShapeDrawable will default
to a RectShape.
AndroidWallet.blogspot.in
92. Drawable
Three ways to define Drawable
Using an image saved in your project resource.
Using an xml file that defines drawable properties.
Using the normal class constructors.
AndroidWallet.blogspot.in
93. Drawable
Using an image
A simple way to add graphics by referencing an image file
from your project resource.
Supported file types are
• PNG (Preferred)
• JPG (acceptable)
• GIF (discouraged)
Preferred technique for application icons, logos, or other
graphics such as used in a game.
To use an image resource just add your file to the
res/drawable/directory of your project.
AndroidWallet.blogspot.in
94. Drawable
Using an image (conti….)
First do the Binding part.
ImageView iv= new ImageView
Set Image resource.
iv.setImageResource(R.drawable.CDAC_image);
In layouts
<ImageButton android:id="@+id/imageview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/CDAC_image” />
AndroidWallet.blogspot.in
95. Drawable
Using an XML
Once you’ve define your drawable in XML save the file in
the res/drawable/directory of your project.
Then retrieve and instantiate the object by calling
Resource.getDrawable(), passing the resource ID in your
XML file.
let’s assume that below is saved as res/drawable/abc.xml
<transition
Xmlns:android=http://schemas.android.com/apk/res/android>
<item androi:drawable= “@drawable/image_xyz”>
</transition>
AndroidWallet.blogspot.in
96. Drawable
Using an XML (Conti…)
Use that previous xml in your java code.
Resources res = mcontext.getResources();
TrasitionDrawable trans
=(TrasitionDrawable)res.getDrawable(R.drawable.abc);
Imageview image = (Imageview)findViewById(R.Id.imageview1);
Image.SetImageDrawable(trans);
The above code will instantiate the TransitionDrawable and
set it as content of an Imageview.
AndroidWallet.blogspot.in
97. Drawable
Using the normal class constructors.
ShapeDrawable
• When you want to dynamically draw some two
dimensional graphics.
Use Canvas Class.
The Canvas class has its own set of drawing methods that
you can use, like
• drawBitmap(...)
• drawRect(...)
• drawText(...)
AndroidWallet.blogspot.in
98. New UI Design Patterns
DashBoard
Focus on 4-5 most important
section
Highlight what’s new
AndroidWallet.blogspot.in
99. New UI Design Patterns
Quick Action
To do common action quickly
Bring key, app-wide action
screen
Provide ‘Home’ mechanismlogo or dedicated button
AndroidWallet.blogspot.in
100. Menus
Basics
Menu offers an user with a choice of operations that can
be executed.
Android offers three types of menus
Option Menus
•Icon Menu
•Expanded Menu
Context Menu
Sub Menu
AndroidWallet.blogspot.in
101. Menu
Definition
Menus are a common user interface component in many
types of applications.
To provide a familiar and consistent user experience, you
should use the Menu APIs to present user actions and other
options in your activities
Menus should be defined in the xml file rather than
creating them in the code.
<?xml version="1.0"?>
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="@string/action_settings"
android:icon="@drawable/CDAC_Home"
android:id="@+id/action_settings"/>
</menu>
AndroidWallet.blogspot.in
102. Menus
Basics
Inflate the menu resource in
onCreateOptionsMenu() and handle
the onOptionsItemSelected().
In android application menu is one of
the important user interface entity
which provides some action options
for a particular view.
Till API level 10
AndroidWallet.blogspot.in
103. Menus
Option Menu
Displayed when the user presses the menu button
Override the onCreateOptionsMenu() to display the
Menu
Override the onOptionsItemSelected() to handle the
menu click
public boolean onCreateOptionsMenu(Menu m){
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
AndroidWallet.blogspot.in
104. Menus
Context Menu
A context menu is a floating menu that appears when the
user performs a long-click on an element.
Displayed when the user presses the item for a long time
(long click)
Somewhat equivalent to “right click”
Register the view for the context menu by calling
registerForContextMenu()
Override the onCreateContextMenu() for creating the
context Menu
Override the onContextItemSelected() for handling the click
event
AndroidWallet.blogspot.in
105. Question 1-
Make a Applicatin having 5 books details including
Name, Price, Author, Rating, Publication ?
AndroidWallet.blogspot.in
107. User Interface
Dialog Boxes
A window that appears in front of the current activity
The underlying activity loses focus and the dialog gets all
user interaction
Displays messages to the users by grabbing their attention
Dialogs are generally used for displaying notifications and
short activities related to the application
AndroidWallet.blogspot.in
108. User Interface
Diff types of Dialog boxes
Android supports these types of Dialogs
• AlertDialog
• ProgressDialog
• DatePickerDialog
• TimePickerDialog
• CustomDialog
AndroidWallet.blogspot.in
109. Dialog
Creation Of Dialog
Life cycle is managed by the framework
Activity.showDialog(int) is used to launch a dialog box
• The parameter is the dialog id that is used to identify a
specific Dialog
Activity.onCreateDialog() is invoked to create the dialog
instance upon the call of showDialog()
Activity.onPrepareDialog() is invoked just before the
dialog is displayed
AndroidWallet.blogspot.in
110. Dialog
Dismissing of Dialog
Activity.removeDialog() dismisses the dialog and removes
any internal references to the dialog managed by Activity
• dismiss() from within the dialog object or
• dismissDialog(int) from the activity can also be used to dismiss a
dialog
The dismiss listener is used to perform some post dismiss
operations once the dialog is dismissed
• onDismiss() of the OnDismissListener interface
The dialog is said to be cancelled if the user presses the
back button or call the cancel() explicitly
Implement the OnCancelListener to handle the cancel
operations explicitly
AndroidWallet.blogspot.in
111. Dialog
Alert Dialog
An AlertDialog is an extension of Dialog class
Its one of the most widely used dialog type
Can be created with any of the following features
•A Title
•Message
•One, Two or Three Buttons
•A list of selectable items (with optional checkboxes or radio
buttons)
AlertDialog is created by using the AlertDialog.Builder
Subclass
Use the builder to construct the dialog
Call the create from the builder to create the dialog.
AndroidWallet.blogspot.in
112. Dialog
Adding Buttons
Buttons can be added to the dialog using the set +/Button() on the builder object.
.setPositiveButton("O,K", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.finish();}
})
.setNegativeButton(“NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Dialog.cancel ();}
})
AndroidWallet.blogspot.in
113. Dialog
Adding a list
A list of items can be added by invoking the setItems() of
the builder.
114. Dialog
Progress Dialog
ProgressDialog is an extension of AlertDialog
Displays progress animation in the form of
• A spinning wheel with undefined progress
• A progress bar with defined progress
Initialize the ProgressDialog with the constructor
Set the Style (spinner or progress bar)
Call the show() method
Call the setProgress() to set the new progress
• Valid only for progress bar style progress dialog
115. Dialog
Custom Dialog
An alert dialog with a custom layout.
Define a new layout xml
Using the inflating service, create an inflated view
Set this inflated view as the view of the dialog by calling
the setView() of the builder object
117. Data Storage - Parts
Option Available
Application can store there own private data in the
phone system.
These data cannot be accessed by other applications
•Security model prevents them
Some of the options available are
• Preferences
• Files
• Databases
Sharing is done by implementing ContentProvider (CP)
• Discussed later…
AndroidWallet.blogspot.in
118. Data Storage - Parts
Preferences
Preferences are used to store the simple application state
in the form of key / value pairs
These data include
o Application configuration
o User preferences such as
• Selected music theme
• Preferred background color
• Highest score so far etc…
getSharedPreference() method is invoked to create or
modify the shared preference
Shared Preference is shared by all the components of the
application
AndroidWallet.blogspot.in
119. Data Storage - Parts
To get a SharedPreferences object
getSharedPreferences() - Use this if you need multiple
preferences files identified by name, which you specify with
the first parameter.
getPreferences() - Use this if you need only one preferences
file for your Activity. Because this will be the only preferences
file for your Activity, you don't supply a name.
AndroidWallet.blogspot.in
120. Data Storage - Parts
Files
It’s a good practice to use preferences and databases to
store app data
But there are times where a direct file I/O is required.
Like the binary state of the game
Storing of the modified image from the image editor
Recording a FM broadcasting* …
The activity class provides the following methods
• openFileOutput()
• openFileInput()
AndroidWallet.blogspot.in
121. Data Storage - Files
If the file exist while creating, it will be overwritten
The Context.MODE_APPEND is used to append to an
existing file.
The files created by default will be accessed only by the
app that created it.
The sharing of files can be enabled by specifying the
constants
• Context.MODE_WORLD_READABLE
• Context.MODE_WORLD_WRITABLE
A more standard way of sharing the data is through the
usage of Content Providers
AndroidWallet.blogspot.in
122. Data Storage - Parts
Context.MODE_WORLD_READABLE
This constant was deprecated in API level 17.
Creating world-readable files is very dangerous, and likely to
cause security holes in applications.
It is strongly discouraged; instead, applications should use
more formal mechanism for interactions such as
ContentProvider , BroadcastReceiver , and Service.
There are no guarantees that this access mode will remain
on a file, such as when it goes through a backup and restore.
File creation mode: allow all other applications to have read
access to the created file.
AndroidWallet.blogspot.in
123. Data Storage - Parts
DataBase
Android provides the following structured storage
Models
Databases
• Uses SQLite relational database
• Every application can create and manage its own
database
Content Providers
• Provides generic and well defined interface for using
and sharing data
AndroidWallet.blogspot.in
124. Data Storage - Parts
SQLite
SQLite is a well known relational databases
It is
• Open Source
• Standards complaint
• Light-Weight
• Single-Tier
It is implemented as a compact C library and included in
the Android’s software stack.
AndroidWallet.blogspot.in
125. Data Storage - Parts
SQLite
Being a library, SQLite becomes a part of the application
that created it reducing
• External Dependencies
• Minimize Latencies
• Simplifies Transaction Locking and Synchronization
SQLite is has been a choice for many consumer
electronics devices
• MP3 player, iPhone, iPod Touch and now Android
Visit the official site of SQLite
• http://www.sqlite.org
• Android docs doesn’t include complete documentation of
SQLite, visit the sqlite site instead
AndroidWallet.blogspot.in
126. Data Storage - Parts
ContentValues and Cursor
ContentValue is used to insert new rows into the table
Each CV object represents a single table row as a map of
columns and their values
Queries in Android are represented as Cursor object.
Cursors provides managed way of controlling the row
position in the result set of the query
AndroidWallet.blogspot.in
127. Data Storage - Parts
Cursor
Some of the navigational methods provided by cursor
• moveToFirst()
• moveToNext()
• moveToPrevious()
• moveToLast()
• getCount()
• getColumnName()
Please refer the SDK documentation for the complete list of
Methods
Android simplifies the management of cursors lifetime by
implementing two apis
• startManagingCursor()
• stopManagingCursor()
AndroidWallet.blogspot.in
128. Data Storage - Parts
Working with SQLite Database
Implementing a DB helper
The SQLiteOpenHelper is an abstract class used to
implement the best practices for
• Creation
• Opening
• Updgrading of databases
By implementing the DB helper, the logic creating or
upgrading the database before it is opened.
The DB helper class overrides the constructor, onCreate
and onUpgrade methods of the SQLiteOpenHelper class
AndroidWallet.blogspot.in
129. Data Storage - Parts
Working with SQLite Database (Cont..)
To use the DB helper, create the instance of the DB
helper class by passing the context, database name,
current version and the CursorFactory (or null for
default)
Call the getReadableDatabase() / getWriteableDatabase()
to get the readable or the writeable instance of the
database
AndroidWallet.blogspot.in
130. Data Storage - Parts
Inserting Data
The writeable DB allows the rows to be inserted,
updated or deleted.
Create an instance of ContentValue class to insert a new
row into the target database
Call the put() passing the column name and its value.
• Check out for the various overloads of the put() method
Repeat this for all the columns of the table.
AndroidWallet.blogspot.in
131. Data Storage - Parts
Inserting Data Process
Call the insert() on the SQLite database instance
The updation is also done in the similar fashion using the
update() method but a “where” condition has to be specified
Without the where clause.
Deletion is done by calling the delete() method with a
“where” condition
AndroidWallet.blogspot.in
132. Data Storage - Parts
SQLite
The following data types are supported in SQLite
• NULL
• INTEGER
• REAL (double)
• TEXT
• BLOB (Binary large object)[store bin data]
The types are dynamically typed while reading or writing
in the application
AndroidWallet.blogspot.in
133. Data Storage - Parts
Querying
Each SQLite database query returns a Cursor object
Letting android to manage the resources more efficiently
To execute the query, invoke the query method with the
following parameters
•A boolean to specify the distinct results or not
•The name of the table
•A projection, list to columns to include in the result set
•A where clause
•A array of selection args to replace the “?” (parameterized
query)
•A group by clause
•A having filters
•A order by expression
•A limit of rows to return
AndroidWallet.blogspot.in
134. Data Storage - Parts
Querying Method
public Cursor query (String table, String[] columns, String
selection, String[] selectionArgs, String groupBy, String
having, String orderBy)
Query the given table, returning a Cursor over the result set.
AndroidWallet.blogspot.in
135. Data Storage - Parts
Query – Extracting data
The moveTo_ABC methods can be used to position the
cursor at a particular row.
The get_ABC method can be used to extract the value by
passing the column name
Cursor c = db.query("keywords", null, null, null, null, null,
null);
/*if (c.moveToFirst()) {
String key = c.getString(c.getColumnIndex("name"));
Toast.makeText(this, key, Toast.LENGTH_LONG).show();
}*/
AndroidWallet.blogspot.in
137. Broadcast Listeners
Notifications
Notify the user
• From a component that is not showing any UI
Means
• Show something in the status bar
• Play some sound
• Vibrate the phone
AndroidWallet.blogspot.in
138. Broadcast Listeners
Broadcast Notification
Are essentially “events’
• That the applications can listen to
System generated
• Low battery
• Ac plugged in or plugged out
• Picture taken
Custom broadcast (generated by apps)
• File download completed
• Sms received
AndroidWallet.blogspot.in
139. Broadcast Listeners
A broadcast receiver (short receiver) is an Android
component which allows you to register for system or
application events.
All registered receivers for an event will be notified by the
Android runtime once this event happens.
141. Broadcast Notifications
Examples
For instance, a Broadcast receiver triggers battery Low
notification that you see on your mobile screen.
Other instances caused by a Broadcast Receiver are new
friend notifications, new friend feeds, new message etc. on
your Facebook app.
In fact, you see broadcast receivers at work all the
time. Notifications like incoming messages, WiFi
Activated/Deactivated message etc. are all real-time
announcements of what is happening in the Android system
and the applications.
AndroidWallet.blogspot.in
142. Broadcast Notifications
Classes of Broadcasts
The two major classes of broadcasts are:
1) Ordered Broadcasts: These broadcasts are synchronous, and
therefore follow a specific order. The order is defined using android:
priority attribute. The receivers with greater priority would receive
the broadcast first. In case there are receivers with same priority
levels, the broadcast would not follow an order.
2) Normal Broadcasts: Normal broadcasts are not orderly. Therefore,
the registered receivers often run all at the same time. This is very
efficient, but the Receivers are unable to utilize the results.
Sometimes to avoid system overload, the system delivers the broadcasts
one at a time, even in case of normal broadcasts. However, the receivers
still cannot use the results.
AndroidWallet.blogspot.in
143. Broadcast Notifications
Difference between Activity Intent
and Broadcasting Intent
You must remember that Broadcasting Intents are different
from the Intents used to start an Activity or a Service
(discussed in previous Android Tutorials).
The intent used to start an Activity makes changes to an
operation the user is interacting with, so the user is aware of
the process.
However, in case of broadcasting intent, the operation runs
completely in the background, and is therefore invisible to
the user.
AndroidWallet.blogspot.in
144. Broadcast Notifications
Implementing the Broadcast Receiver
You need to follow these steps to implement a broadcast
receiver:
1) Create a subclass of Android’s BroadcastReceiver
2) Implement the onReceive() method: In order for the
notification to be sent, an onReceive() method has to be
implemented. Whenever the event for which the receiver is
registered occurs, onReceive() is called. For instance, in case
of battery low notification, the receiver is registered to
Intent.ACTION_BATTERY_LOW event. As soon as the battery
level falls below the defined level, this onReceive() method is
called.
AndroidWallet.blogspot.in
145. Broadcast Notifications
OnReceive
Following are the two arguments of the onReceive()
method:
Context: This is used to access additional information, or to
start services or activities.
Intent: The Intent object is used to register the receiver.
AndroidWallet.blogspot.in
148. Multimedia Framework
Framework
Visit the android-docs/dev guide/appendix/supported
media formats
The android.media package supports the following classes
• AsyncPlayer: Plays the audio is a separate thread
• MediaPlayer: Plays audio and video
• MediaRecorder: Records audio and video
• JetPlayer: Adds sound support for the apps
AndroidWallet.blogspot.in
149. Multimedia Framework
Features
The multi-media features of the android platform falls in
three categories
• Still Image (captured from a camera)
• Audio (Recording and Playback using Mic)
• Video (Recording and Playback using Camera and Mic)
AndroidWallet.blogspot.in
150. Multimedia
Camera
Still images are captured using the Camera
• android.hardware.Camera class
Uses SurfaceView to show the preview of the camera
SurfaceView provides a dedicated drawing surface
embedded inside a view hierarchy
SurfaceView takes care of placing the surface at the
correct location of the screen
The surface is z-ordered.
• The surface is behind the window holding the surface
view
AndroidWallet.blogspot.in