Download - Android Application (Report)
A REPORT
ON
Android Application Development
BY
Akash Khaitan 08DDCS547
AT
Sevya It Pvt Ltd Hyderabad
An Internship Program-III Station of
Faculty of Science and Technology
The ICFAI University Dehradun
June 2012
A REPORT
ON
Android Application Development
BY
Akash Khaitan 08DDCS547
Prepared in Partial Fulfillment of the
IP 401 Internship ProgramndashIII Course
AT
Sevya It Pvt Ltd Hyderabad
An Internship Program-III Station of
Faculty of Science and Technology
The ICFAI University Dehradun
June 2012
Acknowledgement
We would like to express our gratitude to Prof RCRamola center head FACULTY OF
SCIENCE AND TECHNOLOGY Prof TK Mandal IP coordinator FACULTY OF SCIENCE
AND TECHNOLOGY and towards all the faculty members for allowing us in taking the
industrial training according to the our curriculum and to bring about industrial awareness This
training at Sevya It Pvt Ltd gave me an opportunity to realize the ways the IT industries work
and the problem it faces during the course
I also thank Mr Srikant Reddy Modugula (Director) Mrs Sivaparvathi Avula (HR) Mr
Narasayya Donepudi (Director) Mr Harsh Gupta Mr Aditya Kumar Mr Kumar Raja
Donthamsetti and Mr Vineet Agarwal of Sevya It Pvt Ltd who tried their best to provide us all
the facilities needed by our team and cooperated in all possible ways
I thank our faculty in charge Dr Gouri Sankhar Brahma who has helped us all throughout with
his guidance and also helped us in the completion of this report
Faculty of Science and Technology
The ICFAI University Dehradun
Station Sevya It Pvt Ltd Center Hyderabad
Duration 5 Months 14 Days Date of Start 2nd Jan 2012
Date of Submission 15th June 2012
Title of the project Android Application Development
ID NoName(s)Discipline(s)of the student(s)
08DDCS547 Akash Khaitan CS
Name(s) and Designation(s) of the expert(s)
Mr Srikant Modugula(Director)
Mr Narasayya Donepudi (Director)
Mrs Sivaparvathi Avula (HR)
Mr Kumar Raja Donthamsetti (Mobile Application Developer)
Mr Vineet Agarwal(Mobile Application Developer)
Name of the
IP Faculty Dr Gouri Sankhar Brahma
Key Words Mobile Application Development Android Application Development
Project Areas Training
Abstract This project deals with Android Application Development which includes application developed using Android SDK and Java Platform It also
include in brief about the game development and web development for android
Signature of Student Signature of IP Faculty
Date Date
Table of Contents 1 Introduction 1
2 Architecture 2
21 Linux Kernel 3
22 Libraries 3
221 Surface Manager 3
222 Media Libraries 3
223 SQLite 3
224 System C library 3
225 LibWebCore 4
226 SGL 4
227 3D libraries 4
228 FreeType 4
23 Android Runtime 4
24 Application Framework 5
25 Applications 5
3 Activity 6
31 Activity Lifecycle 6
32 Context 7
33 Intents 8
34 Data passing between Activities 8
35 Implicit Intent 9
4 Services 10
5 User Interface 11
51 View Group 12
511 Layouts 12
52 Views 15
521 TextView 15
522 EditText 15
523 Spinner 15
524 Button amp Image Button 16
525 ImageView 17
526 CheckBox 17
527 RadioButton 17
528 WebView 18
6 Menus 20
61 Defining a Menu in XML 20
62 Defining Activity class 20
63 Creating Menu 21
64 Handling Menu Click Events 21
7 Navigation 22
71 Tabs 22
711 Create Separate Activity 23
712 Create layout for activity 23
713 Create a layout with Tabhost as the root element 23
714 Add tabs using the activity class which extends TabActivity 24
715 On Tab Changed 25
72 Lists 26
721 Simple Lists 26
722 Custom Lists 27
723 Custom Adapter 28
724 List Activity 29
73 Listener 30
8 Notification 31
81 Toast Notification 32
811 Simple Toast Notification 32
812 Custom Toast Notification 32
82 Status Bar Notifications 34
821 Simple Status Bar Notification 35
822 Custom Status Bar Notification 36
83 Dialogs 37
831 Simple Dialogs 37
832 Custom Dialogs 39
9 Storage Based Application Development 42
91 Shared Preferences 44
911 Writting to SharedPreference 44
912 Retrieving Shared preferences 45
92 Internal Storage 45
921 Writing to Internal Storage 45
922 Retrieving from Internal Storage 46
93 External Storage 47
931 Writing to External Storage 47
932 Retrieving from External Storage 47
94 SQLite Database 48
941 Get Database 49
942 Inserting Data 49
943 Deleting Data 49
944 Updating Data 50
945 Retrieving Data 50
10 Multimedia 51
101 Audio 51
1011 To Record 51
1012 To Play 51
102 Tone Generator 52
103 Video 52
1031 To Play Video 52
11 Mobile Web Apps 53
111 Linking with native Libraries 53
112 UI Look and feel like native application 53
113 Navigation like native application 54
114 Advantages 54
115 Disadvantages 54
12 Game Development 55
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
A REPORT
ON
Android Application Development
BY
Akash Khaitan 08DDCS547
Prepared in Partial Fulfillment of the
IP 401 Internship ProgramndashIII Course
AT
Sevya It Pvt Ltd Hyderabad
An Internship Program-III Station of
Faculty of Science and Technology
The ICFAI University Dehradun
June 2012
Acknowledgement
We would like to express our gratitude to Prof RCRamola center head FACULTY OF
SCIENCE AND TECHNOLOGY Prof TK Mandal IP coordinator FACULTY OF SCIENCE
AND TECHNOLOGY and towards all the faculty members for allowing us in taking the
industrial training according to the our curriculum and to bring about industrial awareness This
training at Sevya It Pvt Ltd gave me an opportunity to realize the ways the IT industries work
and the problem it faces during the course
I also thank Mr Srikant Reddy Modugula (Director) Mrs Sivaparvathi Avula (HR) Mr
Narasayya Donepudi (Director) Mr Harsh Gupta Mr Aditya Kumar Mr Kumar Raja
Donthamsetti and Mr Vineet Agarwal of Sevya It Pvt Ltd who tried their best to provide us all
the facilities needed by our team and cooperated in all possible ways
I thank our faculty in charge Dr Gouri Sankhar Brahma who has helped us all throughout with
his guidance and also helped us in the completion of this report
Faculty of Science and Technology
The ICFAI University Dehradun
Station Sevya It Pvt Ltd Center Hyderabad
Duration 5 Months 14 Days Date of Start 2nd Jan 2012
Date of Submission 15th June 2012
Title of the project Android Application Development
ID NoName(s)Discipline(s)of the student(s)
08DDCS547 Akash Khaitan CS
Name(s) and Designation(s) of the expert(s)
Mr Srikant Modugula(Director)
Mr Narasayya Donepudi (Director)
Mrs Sivaparvathi Avula (HR)
Mr Kumar Raja Donthamsetti (Mobile Application Developer)
Mr Vineet Agarwal(Mobile Application Developer)
Name of the
IP Faculty Dr Gouri Sankhar Brahma
Key Words Mobile Application Development Android Application Development
Project Areas Training
Abstract This project deals with Android Application Development which includes application developed using Android SDK and Java Platform It also
include in brief about the game development and web development for android
Signature of Student Signature of IP Faculty
Date Date
Table of Contents 1 Introduction 1
2 Architecture 2
21 Linux Kernel 3
22 Libraries 3
221 Surface Manager 3
222 Media Libraries 3
223 SQLite 3
224 System C library 3
225 LibWebCore 4
226 SGL 4
227 3D libraries 4
228 FreeType 4
23 Android Runtime 4
24 Application Framework 5
25 Applications 5
3 Activity 6
31 Activity Lifecycle 6
32 Context 7
33 Intents 8
34 Data passing between Activities 8
35 Implicit Intent 9
4 Services 10
5 User Interface 11
51 View Group 12
511 Layouts 12
52 Views 15
521 TextView 15
522 EditText 15
523 Spinner 15
524 Button amp Image Button 16
525 ImageView 17
526 CheckBox 17
527 RadioButton 17
528 WebView 18
6 Menus 20
61 Defining a Menu in XML 20
62 Defining Activity class 20
63 Creating Menu 21
64 Handling Menu Click Events 21
7 Navigation 22
71 Tabs 22
711 Create Separate Activity 23
712 Create layout for activity 23
713 Create a layout with Tabhost as the root element 23
714 Add tabs using the activity class which extends TabActivity 24
715 On Tab Changed 25
72 Lists 26
721 Simple Lists 26
722 Custom Lists 27
723 Custom Adapter 28
724 List Activity 29
73 Listener 30
8 Notification 31
81 Toast Notification 32
811 Simple Toast Notification 32
812 Custom Toast Notification 32
82 Status Bar Notifications 34
821 Simple Status Bar Notification 35
822 Custom Status Bar Notification 36
83 Dialogs 37
831 Simple Dialogs 37
832 Custom Dialogs 39
9 Storage Based Application Development 42
91 Shared Preferences 44
911 Writting to SharedPreference 44
912 Retrieving Shared preferences 45
92 Internal Storage 45
921 Writing to Internal Storage 45
922 Retrieving from Internal Storage 46
93 External Storage 47
931 Writing to External Storage 47
932 Retrieving from External Storage 47
94 SQLite Database 48
941 Get Database 49
942 Inserting Data 49
943 Deleting Data 49
944 Updating Data 50
945 Retrieving Data 50
10 Multimedia 51
101 Audio 51
1011 To Record 51
1012 To Play 51
102 Tone Generator 52
103 Video 52
1031 To Play Video 52
11 Mobile Web Apps 53
111 Linking with native Libraries 53
112 UI Look and feel like native application 53
113 Navigation like native application 54
114 Advantages 54
115 Disadvantages 54
12 Game Development 55
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Acknowledgement
We would like to express our gratitude to Prof RCRamola center head FACULTY OF
SCIENCE AND TECHNOLOGY Prof TK Mandal IP coordinator FACULTY OF SCIENCE
AND TECHNOLOGY and towards all the faculty members for allowing us in taking the
industrial training according to the our curriculum and to bring about industrial awareness This
training at Sevya It Pvt Ltd gave me an opportunity to realize the ways the IT industries work
and the problem it faces during the course
I also thank Mr Srikant Reddy Modugula (Director) Mrs Sivaparvathi Avula (HR) Mr
Narasayya Donepudi (Director) Mr Harsh Gupta Mr Aditya Kumar Mr Kumar Raja
Donthamsetti and Mr Vineet Agarwal of Sevya It Pvt Ltd who tried their best to provide us all
the facilities needed by our team and cooperated in all possible ways
I thank our faculty in charge Dr Gouri Sankhar Brahma who has helped us all throughout with
his guidance and also helped us in the completion of this report
Faculty of Science and Technology
The ICFAI University Dehradun
Station Sevya It Pvt Ltd Center Hyderabad
Duration 5 Months 14 Days Date of Start 2nd Jan 2012
Date of Submission 15th June 2012
Title of the project Android Application Development
ID NoName(s)Discipline(s)of the student(s)
08DDCS547 Akash Khaitan CS
Name(s) and Designation(s) of the expert(s)
Mr Srikant Modugula(Director)
Mr Narasayya Donepudi (Director)
Mrs Sivaparvathi Avula (HR)
Mr Kumar Raja Donthamsetti (Mobile Application Developer)
Mr Vineet Agarwal(Mobile Application Developer)
Name of the
IP Faculty Dr Gouri Sankhar Brahma
Key Words Mobile Application Development Android Application Development
Project Areas Training
Abstract This project deals with Android Application Development which includes application developed using Android SDK and Java Platform It also
include in brief about the game development and web development for android
Signature of Student Signature of IP Faculty
Date Date
Table of Contents 1 Introduction 1
2 Architecture 2
21 Linux Kernel 3
22 Libraries 3
221 Surface Manager 3
222 Media Libraries 3
223 SQLite 3
224 System C library 3
225 LibWebCore 4
226 SGL 4
227 3D libraries 4
228 FreeType 4
23 Android Runtime 4
24 Application Framework 5
25 Applications 5
3 Activity 6
31 Activity Lifecycle 6
32 Context 7
33 Intents 8
34 Data passing between Activities 8
35 Implicit Intent 9
4 Services 10
5 User Interface 11
51 View Group 12
511 Layouts 12
52 Views 15
521 TextView 15
522 EditText 15
523 Spinner 15
524 Button amp Image Button 16
525 ImageView 17
526 CheckBox 17
527 RadioButton 17
528 WebView 18
6 Menus 20
61 Defining a Menu in XML 20
62 Defining Activity class 20
63 Creating Menu 21
64 Handling Menu Click Events 21
7 Navigation 22
71 Tabs 22
711 Create Separate Activity 23
712 Create layout for activity 23
713 Create a layout with Tabhost as the root element 23
714 Add tabs using the activity class which extends TabActivity 24
715 On Tab Changed 25
72 Lists 26
721 Simple Lists 26
722 Custom Lists 27
723 Custom Adapter 28
724 List Activity 29
73 Listener 30
8 Notification 31
81 Toast Notification 32
811 Simple Toast Notification 32
812 Custom Toast Notification 32
82 Status Bar Notifications 34
821 Simple Status Bar Notification 35
822 Custom Status Bar Notification 36
83 Dialogs 37
831 Simple Dialogs 37
832 Custom Dialogs 39
9 Storage Based Application Development 42
91 Shared Preferences 44
911 Writting to SharedPreference 44
912 Retrieving Shared preferences 45
92 Internal Storage 45
921 Writing to Internal Storage 45
922 Retrieving from Internal Storage 46
93 External Storage 47
931 Writing to External Storage 47
932 Retrieving from External Storage 47
94 SQLite Database 48
941 Get Database 49
942 Inserting Data 49
943 Deleting Data 49
944 Updating Data 50
945 Retrieving Data 50
10 Multimedia 51
101 Audio 51
1011 To Record 51
1012 To Play 51
102 Tone Generator 52
103 Video 52
1031 To Play Video 52
11 Mobile Web Apps 53
111 Linking with native Libraries 53
112 UI Look and feel like native application 53
113 Navigation like native application 54
114 Advantages 54
115 Disadvantages 54
12 Game Development 55
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Faculty of Science and Technology
The ICFAI University Dehradun
Station Sevya It Pvt Ltd Center Hyderabad
Duration 5 Months 14 Days Date of Start 2nd Jan 2012
Date of Submission 15th June 2012
Title of the project Android Application Development
ID NoName(s)Discipline(s)of the student(s)
08DDCS547 Akash Khaitan CS
Name(s) and Designation(s) of the expert(s)
Mr Srikant Modugula(Director)
Mr Narasayya Donepudi (Director)
Mrs Sivaparvathi Avula (HR)
Mr Kumar Raja Donthamsetti (Mobile Application Developer)
Mr Vineet Agarwal(Mobile Application Developer)
Name of the
IP Faculty Dr Gouri Sankhar Brahma
Key Words Mobile Application Development Android Application Development
Project Areas Training
Abstract This project deals with Android Application Development which includes application developed using Android SDK and Java Platform It also
include in brief about the game development and web development for android
Signature of Student Signature of IP Faculty
Date Date
Table of Contents 1 Introduction 1
2 Architecture 2
21 Linux Kernel 3
22 Libraries 3
221 Surface Manager 3
222 Media Libraries 3
223 SQLite 3
224 System C library 3
225 LibWebCore 4
226 SGL 4
227 3D libraries 4
228 FreeType 4
23 Android Runtime 4
24 Application Framework 5
25 Applications 5
3 Activity 6
31 Activity Lifecycle 6
32 Context 7
33 Intents 8
34 Data passing between Activities 8
35 Implicit Intent 9
4 Services 10
5 User Interface 11
51 View Group 12
511 Layouts 12
52 Views 15
521 TextView 15
522 EditText 15
523 Spinner 15
524 Button amp Image Button 16
525 ImageView 17
526 CheckBox 17
527 RadioButton 17
528 WebView 18
6 Menus 20
61 Defining a Menu in XML 20
62 Defining Activity class 20
63 Creating Menu 21
64 Handling Menu Click Events 21
7 Navigation 22
71 Tabs 22
711 Create Separate Activity 23
712 Create layout for activity 23
713 Create a layout with Tabhost as the root element 23
714 Add tabs using the activity class which extends TabActivity 24
715 On Tab Changed 25
72 Lists 26
721 Simple Lists 26
722 Custom Lists 27
723 Custom Adapter 28
724 List Activity 29
73 Listener 30
8 Notification 31
81 Toast Notification 32
811 Simple Toast Notification 32
812 Custom Toast Notification 32
82 Status Bar Notifications 34
821 Simple Status Bar Notification 35
822 Custom Status Bar Notification 36
83 Dialogs 37
831 Simple Dialogs 37
832 Custom Dialogs 39
9 Storage Based Application Development 42
91 Shared Preferences 44
911 Writting to SharedPreference 44
912 Retrieving Shared preferences 45
92 Internal Storage 45
921 Writing to Internal Storage 45
922 Retrieving from Internal Storage 46
93 External Storage 47
931 Writing to External Storage 47
932 Retrieving from External Storage 47
94 SQLite Database 48
941 Get Database 49
942 Inserting Data 49
943 Deleting Data 49
944 Updating Data 50
945 Retrieving Data 50
10 Multimedia 51
101 Audio 51
1011 To Record 51
1012 To Play 51
102 Tone Generator 52
103 Video 52
1031 To Play Video 52
11 Mobile Web Apps 53
111 Linking with native Libraries 53
112 UI Look and feel like native application 53
113 Navigation like native application 54
114 Advantages 54
115 Disadvantages 54
12 Game Development 55
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Table of Contents 1 Introduction 1
2 Architecture 2
21 Linux Kernel 3
22 Libraries 3
221 Surface Manager 3
222 Media Libraries 3
223 SQLite 3
224 System C library 3
225 LibWebCore 4
226 SGL 4
227 3D libraries 4
228 FreeType 4
23 Android Runtime 4
24 Application Framework 5
25 Applications 5
3 Activity 6
31 Activity Lifecycle 6
32 Context 7
33 Intents 8
34 Data passing between Activities 8
35 Implicit Intent 9
4 Services 10
5 User Interface 11
51 View Group 12
511 Layouts 12
52 Views 15
521 TextView 15
522 EditText 15
523 Spinner 15
524 Button amp Image Button 16
525 ImageView 17
526 CheckBox 17
527 RadioButton 17
528 WebView 18
6 Menus 20
61 Defining a Menu in XML 20
62 Defining Activity class 20
63 Creating Menu 21
64 Handling Menu Click Events 21
7 Navigation 22
71 Tabs 22
711 Create Separate Activity 23
712 Create layout for activity 23
713 Create a layout with Tabhost as the root element 23
714 Add tabs using the activity class which extends TabActivity 24
715 On Tab Changed 25
72 Lists 26
721 Simple Lists 26
722 Custom Lists 27
723 Custom Adapter 28
724 List Activity 29
73 Listener 30
8 Notification 31
81 Toast Notification 32
811 Simple Toast Notification 32
812 Custom Toast Notification 32
82 Status Bar Notifications 34
821 Simple Status Bar Notification 35
822 Custom Status Bar Notification 36
83 Dialogs 37
831 Simple Dialogs 37
832 Custom Dialogs 39
9 Storage Based Application Development 42
91 Shared Preferences 44
911 Writting to SharedPreference 44
912 Retrieving Shared preferences 45
92 Internal Storage 45
921 Writing to Internal Storage 45
922 Retrieving from Internal Storage 46
93 External Storage 47
931 Writing to External Storage 47
932 Retrieving from External Storage 47
94 SQLite Database 48
941 Get Database 49
942 Inserting Data 49
943 Deleting Data 49
944 Updating Data 50
945 Retrieving Data 50
10 Multimedia 51
101 Audio 51
1011 To Record 51
1012 To Play 51
102 Tone Generator 52
103 Video 52
1031 To Play Video 52
11 Mobile Web Apps 53
111 Linking with native Libraries 53
112 UI Look and feel like native application 53
113 Navigation like native application 54
114 Advantages 54
115 Disadvantages 54
12 Game Development 55
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
525 ImageView 17
526 CheckBox 17
527 RadioButton 17
528 WebView 18
6 Menus 20
61 Defining a Menu in XML 20
62 Defining Activity class 20
63 Creating Menu 21
64 Handling Menu Click Events 21
7 Navigation 22
71 Tabs 22
711 Create Separate Activity 23
712 Create layout for activity 23
713 Create a layout with Tabhost as the root element 23
714 Add tabs using the activity class which extends TabActivity 24
715 On Tab Changed 25
72 Lists 26
721 Simple Lists 26
722 Custom Lists 27
723 Custom Adapter 28
724 List Activity 29
73 Listener 30
8 Notification 31
81 Toast Notification 32
811 Simple Toast Notification 32
812 Custom Toast Notification 32
82 Status Bar Notifications 34
821 Simple Status Bar Notification 35
822 Custom Status Bar Notification 36
83 Dialogs 37
831 Simple Dialogs 37
832 Custom Dialogs 39
9 Storage Based Application Development 42
91 Shared Preferences 44
911 Writting to SharedPreference 44
912 Retrieving Shared preferences 45
92 Internal Storage 45
921 Writing to Internal Storage 45
922 Retrieving from Internal Storage 46
93 External Storage 47
931 Writing to External Storage 47
932 Retrieving from External Storage 47
94 SQLite Database 48
941 Get Database 49
942 Inserting Data 49
943 Deleting Data 49
944 Updating Data 50
945 Retrieving Data 50
10 Multimedia 51
101 Audio 51
1011 To Record 51
1012 To Play 51
102 Tone Generator 52
103 Video 52
1031 To Play Video 52
11 Mobile Web Apps 53
111 Linking with native Libraries 53
112 UI Look and feel like native application 53
113 Navigation like native application 54
114 Advantages 54
115 Disadvantages 54
12 Game Development 55
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
832 Custom Dialogs 39
9 Storage Based Application Development 42
91 Shared Preferences 44
911 Writting to SharedPreference 44
912 Retrieving Shared preferences 45
92 Internal Storage 45
921 Writing to Internal Storage 45
922 Retrieving from Internal Storage 46
93 External Storage 47
931 Writing to External Storage 47
932 Retrieving from External Storage 47
94 SQLite Database 48
941 Get Database 49
942 Inserting Data 49
943 Deleting Data 49
944 Updating Data 50
945 Retrieving Data 50
10 Multimedia 51
101 Audio 51
1011 To Record 51
1012 To Play 51
102 Tone Generator 52
103 Video 52
1031 To Play Video 52
11 Mobile Web Apps 53
111 Linking with native Libraries 53
112 UI Look and feel like native application 53
113 Navigation like native application 54
114 Advantages 54
115 Disadvantages 54
12 Game Development 55
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
121 Accelerometer Based Games 55
122 Getting Accelerometer Readings 55
123 Building Game 56
1231 Main Activity class 56
1232 Create Custom View 57
1233 Creating Stage Screens 57
Conclusion ix
References x
Glossary xi
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Introduction 1
1 Introduction
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 begin
developing applications on the Android platform using the Java programming language
This report describes some of the below topics in details
Architecture
Activity
Services
User Interface
Menus
Navigation
Notifications
Data Storage Techniques
Multimedia
Game Development
Web Application Development
Figure 1 Android
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Architecture 2
2 Architecture
Android Architecture contains the following layers-
Linux Kernel
Libraries
Android Run time
Application Framework
Applications
The below Figure 2 shows the complete android architecture
Figure 2 Android Architecture
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Architecture 3
21 Linux Kernel
Android relies on Linux version 26 for core system services such as security memory
management process management network stack and driver model The kernel also acts as
abstraction layer between the hardware and the rest of the software stack
22 Libraries
Android includes a set of CC++ libraries used by various components of the Android system
These capabilities are exposed to developers through the Android application framework Some
of the core libraries are listed below
221 Surface Manager
Manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers
from multiple applications
222 Media Libraries
Based on Packet Videos Open CORE the libraries support playback and recording of many
popular audio and video formats as well as static image files including MPEG4 H264 MP3
AAC AMR JPG and PNG
223 SQLite
A powerful and lightweight relational database engine available to all applications
224 System C library
A BSD-derived implementation of the standard C system library (libc) tuned for embedded
Linux-based devices
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Architecture 4
225 LibWebCore
A modern web browser engine which powers both the Android browser and an embeddable web
view
226 SGL
The underlying 2D graphics engine
227 3D libraries
An implementation based on Open GL ES 10 APIs the libraries use either Hardware 3D
acceleration (where available) or the included highly optimized 3D software 14rasterizer
228 FreeType
Bitmap and vector font rendering
23 Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the
core libraries of the Java programming language
Every Android application runs in its own process with its own instance of the Dalvik virtual
machine Dalvik has been written so that a device can run multiple VMs efficiently The Dalvik
VM executes files in the Dalvik Executable (dex) format which is optimized for minimal
memory footprint The VM is register-based and runs classes compiled by a Java language
compiler that have been transformed into the dex format by the included dx tool The Dalvik
VM relies on the Linux kernel for underlying functionality such as threading and low-level
memory management
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Architecture 5
24 Application Framework
By providing an open development platform Android offers developers the ability to build
extremely rich and innovative applications Developers are free to take advantage of the device
hardware access location information run background services set alarms and add notifications
to the status bar and much much more Developers have full access to the same framework
APIs used by the core applications The Application architecture is designed to simplify the
reuse of components Underlying all applications is a set of services and systems including
A rich and extensible set of Views that can be used to build an application including
lists grids text boxes buttons and even an embeddable web browser
Content Providers that enable applications to access data from other applications (such as
Contacts) or to share their own data
A Resource Manager providing access to non-code resources such as localized strings
Graphics and layout files
A Notification Manager that enables all applications to display custom alerts in the status
bar
An Activity Manager that manages the lifecycle of applications and provides a common
Navigation back stack
25 Applications
Android will ship with a set of core applications including an email client SMS program
calendar maps browser contacts and others All applications are written using the Java
programming language
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Activity 6
3 Activity
An Activity is an application component that provides a screen with which users can interact in
order to do something such as dial the phone take a photo send an email or view a map Each
activity is given a window in which to draw its user interface The window typically fills the
screen but may be smaller than the screen and float on top of other windows
An application usually consists of multiple activities that are loosely bound to each other
Typically one activity in an application is specified as the main activity which is presented to
the user when launching the application for the first time Each activity can then start another
activity in order to perform different actions Each time a new activity starts the previous
activity is stopped but the system preserves the activity in a stack (the back stack) When a
new activity starts it is pushed onto the back stack and takes user focus The back stack abides to
the basic last in first out stack mechanism so when the user is done with the current activity
and presses the Back button it is popped from the stack (and destroyed) and the previous activity
resumes
31 Activity Lifecycle
When an activity is stopped because a new activity starts it is notified of this change in state
through the activitys lifecycle callback methods There are several callback methods that an
activity might receive due to a change in its statemdashwhether the system is creating it stopping it
resuming it or destroying itmdashand each callback provides you the opportunity to perform specific
work thats appropriate to that state change When the activity resumes you can reacquire the
necessary resources and resume actions that were interrupted These state transitions are all part
of the activity lifecycle
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Activity 7
Figure 3 Activity Lifecycle
32 Context
Interface to global information about an application environment
This is an abstract class whose implementation is provided by the Android system
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Activity 8
It allows access to application-specific resources and classes as well as up-calls for
application-level operations such as launching activities broadcasting and receiving
intents etc
33 Intents
Intents are asynchronous message which allows Android components to request
functionality from other components of the Android system For example an Activity can
send Intents to the Android system which starts another Activity
Intent can also contain data This data can be used by the receiving component
Android supports explicit and implicit Intents
34 Data passing between Activities
Intent can also carry small amounts of data to be used by the activity that is started
The component which creates the Intent can add data to it via the overloaded putExtra()
method
Extras are keyvalue pairs the key is always a String As value you can use the primitive
data types (int float) String Bundle Serializable
Below illustration shows how intent carries data
Intent intent = new Intent(this ActivityTwoclass)
intentputExtra(Value1 This is Value 1 )
intentputExtra(Value2 This is value 2 )
startActivity(intent)
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Activity 9
Receiving Extra data in sub activityrsquos onCreate() method
Intent intent=getIntent()
String receivedString=intentgetExtras()getString(ldquoValue1rdquo)
35 Implicit Intent
Do not specify the Java class which should be called They specify the action which should be
performed and optionally an URI which should be used for this action
For example if you want to call a number automatically you could have used this intent
Intent in=new Intent(IntentACTION_CALLUriparse(rdquotel9999999999rdquo))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionCALL_PHONEgt
Another example to launch an intent to open the browser and navigate to a
certain URL
Intent in=new Intent(IntentACTION_VIEW Uriparse(httpwwwgooglecom))
startActivity(in)
If you use this it requires adding the following permission to the manifest
file
ltuses-permission androidname=androidpermissionINTERNETgt
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Services 10
4 Services
A service can run in the background to perform work even while the user is in a different
application
A service can allow other components to bind to it in order to interact with it and
perform intercrosses communication
A service runs in the main thread of the application that hosts it by default
Figure 4 Service Lifecycle
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 11
5 User Interface
User interface in android consists of View Groups and Views
Views Views are the base class for all visual interface elements (commonly known as
controls) All UI controls including the layout classes are derived from View
View Groups View Groups are extensions of the View class that can contain multiple
child Views Extend the ViewGroup class to create compound controls made up of
interconnected child Views The ViewGroup class is also extended to provide the layout
managers that help you lay out controls within your Activities
Figure 5 View Group
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 12
51 View Group
511 Layouts
Layout managers (more generally just called layouts) are extensions of the ViewGroup class
used to positioning child controls for your UI Layouts organize views such as grouping together
a button and label or a group of them
Layouts and Views Relationship
Figure 6 Layout amp View Relationship
The Android SDK includes some simple layouts to construct UI The following list
includes layout classes available
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 13
5111 FrameLayout
The Frame Layout simply pins each child view to the top left corner Adding multiple children
stacks each new child on top of the one before with each new View obscuring the last
Figure 7 Frame Layout
5112 LinearLayout
A Linear Layout aligns each child View in either a vertical or a horizontal line A vertical layout
has a column of Views while a horizontal layout has a row of Views An important property for
LinearLayout is orientation and valid options are vertical or horizontal
Figure 8 Linear Layout
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 14
5113 RelativeLayout
The Relative Layout lets you define the positions of each child View relative to the others and to
the screen boundaries
Figure 9 Relative layout
5114 TableLayout
The Table Layout lets you lay out Views using a grid of rows and columns
Figure 10 Table Layout
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 15
52 Views
Android supplies a toolbox of standard Views to help you create simple interfaces By using
these controls (and modifying or extending them as necessary) you can simplify your
development and provide consistency between applications
The following list highlights some of the more familiar toolbox controls
521 TextView
A standard read-only text label It supports multi-line display string formatting and automatic
word wrapping
522 EditText
It accepts multiline entry word-wrapping and hint text Collecting Different Types of Input
By default any text contents within an EditText control is displayed as plain text The default
software keyboard is used for inputting plain text
523 Spinner
A composite control that displays a Text View and an associated List View that lets you select an
item from a list to display in the textbox Itrsquos made from a Text View displaying the current
selection combined with a button that displays a selection dialog when pressed
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 16
Figure 11 Spinner
524 Button amp Image Button
A standard push-button Android SDK includes two simple button controls for use within your
layouts Button (androidwidgetButton) and ImageButton (androidwidgetImageButton) These
controls function in a similar way but the difference between the controls is mostly visual the
Button control has a text label whereas the ImageButton uses an image drawable resource
instead
Figure 12 Button Figure 13 Image Button
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 17
525 ImageView
A View which can load images from various sources (such as resources) and display to the user
It can and provides various display options such as scaling
Figure 14 ImageView
526 CheckBox
A two-state button represented by a checked or unchecked box
527 RadioButton
A two-state grouped button A group of these presents the user with a number of binary options
of which only one can be enabled at a time
Working with RadioGroup Controls
A RadioGroup control is simply a container for RadioButton controls but it does have some
useful properties For example you can have horizontal and vertical radio button groups This is
set using the the androidorientation attribute
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 18
Figure 15 Radio Button
528 WebView
A View that displays web pages This class is used roll own web browser or simply display some
online content within your Activity
To add a WebView to your Application simply include the ltWebViewgt element in your
activity layout For example
Figure 16 User Created Content Figure 17 Web Content
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
User Interface 19
ltxml version=10 encoding=utf-8gt
ltWebView xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idwebview
androidlayout_width=fill_parent
androidlayout_height=fill_parent
gt
To load a web page in the WebView use loadUrl() For example
WebView webView = (WebView) findViewById(Ridwebview)
webViewloadUrl(httpwwwgooglecom)
You can also load from an HTML string
String summary = lthtmlgtltbodygtYou scored ltbgt192ltbgt pointsltbodygtlthtmlgt
webviewloadData(summary texthtml null)
In order for your Activity to access the Internet and load web pages in a WebView you
must add the INTERNET permissions to your Android Manifest file
ltmanifest gt
ltuses-permission androidname=androidpermissionINTERNET gt
ltmanifestgt
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Menus 20
6 Menus
Menus are a common user interface component in many types of applications To provide a
familiar and consistent user experience one should use the Menu APIs to present user actions
and other options in your activities
Objective The below described application plays songs
when the play is clicked from menu and pauses when the
pause button is clicked from menu
61 Defining a Menu in XML
Here the menuxml is defined
ltxml version=10 encoding=utf-8gt
ltmenu xmlnsandroid=httpschemasandroidcomapkresandroid gt
ltitem androidid=+idplay androidicon=androiddrawableic_media_play
androidtitle=Playgtltitemgt
ltitem androidid=+idstop
androidicon=androiddrawableic_media_pause
androidtitle=Stopgtltitemgt
ltmenugt
62 Defining Activity class
As per the objective the activity class creates media player object with the song illustrated below
public class MenuActivity extends Activity
Called when the activity is first created
MediaPlayer mp
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
mp = new MediaPlayer()
try
mpsetDataSource(EnvironmentgetExternalStorageDirectory()getAbsoluteP
ath()+Music+Flute Artmp3)
catch (IllegalArgumentException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IllegalStateException e)
Figure 18 Menu
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Menus 21
eprintStackTrace()
catch (IOException e)
eprintStackTrace()
63 Creating Menu
The below code of lines inflates the menuxml to the menu of the activity Thus a menu is
successfully created
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater()
inflaterinflate(Rmenumenu menu)
return true
64 Handling Menu Click Events
When the user selects an item from the options menu the system calls activitys
onOptionsItemSelected() method The method passes the MenuItem selected which can be
identified by calling getItemId() See the code given below
public boolean onOptionsItemSelected(MenuItem item)
switch (itemgetItemId())
case Ridplay
try
mpprepare()
catch (IllegalStateException e)
TODO Auto-generated catch block
eprintStackTrace()
catch (IOException e)
TODO Auto-generated catch block
eprintStackTrace()
mpstart()
break
case Ridstop
mppause()
break
return true
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 22
7 Navigation
This section covers components for interactive navigation for user The components to be
discussed in the chapter are
Tabs
lists
71 Tabs
Use of tabs is essential navigation feature supported by android where users of the application
can view different activity in the same page in
different tabs
A tabhost consists of a tab widget for the tabs
and frame layout for the activity space
Objective To create a tab view consisting of
three tabs with a different activity on each tab
Steps Involved
Create three separate Activities
Create three different layouts for activities
Create a layout with Tabhost as the root element
Add tabs using the activity class which extends TabActivity
Figure 19 Tabs
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 23
711 Create Separate Activity
Here one activity is illustrated create other two
package comsoulastraltab
import androidappActivity
import androidosBundle
public class Email extends Activity
Override
protected void onCreate(Bundle savedInstanceState)
TODO Auto-generated method stub
superonCreate(savedInstanceState)
setContentView(Rlayoutemail)
712 Create layout for activity
Create a layout for above activity which is to be set in set content view of the activity
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Email Activitygt
ltLinearLayoutgt
713 Create a layout with Tabhost as the root element
ltxml version=10 encoding=utf-8gt
ltTabHost xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=androididtabhost
androidlayout_width=fill_parent
androidlayout_height=fill_parentgt
ltLinearLayout
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 24
androidorientation=vertical
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dpgt
ltTabWidget
androidid=androididtabs
androidlayout_width=fill_parent
androidlayout_height=wrap_content gt
ltFrameLayout
androidid=androididtabcontent
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=5dp gt
ltLinearLayoutgt
ltTabHostgt
714 Add tabs using the activity class which extends TabActivity
package comsoulastraltab
import androidRanim
import androidRdrawable
import androidappActivity
import androidappTabActivity
import androidcontentIntent
import androidcontentresResources
import androidgraphicsdrawableDrawable
import androidosBundle
import androidwidgetTabHost
import androidwidgetTabHostOnTabChangeListener
public class Tab extends TabActivity implements OnTabChangeListener
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
TabHost tabHost=getTabHost()
TabHostTabSpec spec
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 25
Intent intent
Resources res = getResources()
intent = new Intent()setClass(this Emailclass)
spec =
tabHostnewTabSpec(email)setIndicator(EmailresgetDrawable(drawablesym
_action_email))setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(this Callclass)
spec = tabHostnewTabSpec(call)setIndicator(Call
resgetDrawable(drawablesym_action_call))
setContent(intent)
tabHostaddTab(spec)
intent = new Intent()setClass(thisChatclass)
spec = tabHostnewTabSpec(chat)setIndicator(Chat
resgetDrawable(drawablesym_action_chat))
setContent(intent)
tabHostaddTab(spec)
tabHostsetOnTabChangedListener(this)
715 On Tab Changed
Listener when tab is switched
Override
public void onTabChanged(String tabId)
TODO Auto-generated method stub
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 26
72 Lists
The list in android displays the items in the list format and clicking events on the list item is
managed by the programmer
The section describes
Simple Lists(Default List) Contains a default row layout and takes Array adapter
Custom Lists Row layout and custom adapter is defined by the programmer
In order to completely understand list one must understand the concept of adapters
Adapters Adapter binds the data from array to the row layout of the list and runs up to the
length of the array implicitly and thus populates the list
721 Simple Lists
Objective To create a simple list
Extend listActivity
setListAdapter with normal
ArrayadapterltStringgt and simple_list_item_1 layout
package comsoulastralsimplelist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidviewView
import androidwidgetAdapterView
import androidwidgetAdapterViewOnItemClickListener
import androidwidgetArrayAdapter
Figure 20 S imple List
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 27
import androidwidgetListView
import androidwidgetToast
public class SimpleListActivity extends ListActivity
Called when the activity is first created
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
setListAdapter(new
ArrayAdapterltStringgt(thisandroidRlayoutsimple_list_item_1
ACTIVITY_CHOICES))
722 Custom Lists
Objective To create custom row layout custom
adapter and custom list with an arrow image
7221 Custom Row
Create a row xml as shown below
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
Figure 21 Custom List
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 28
ltLinearLayout androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidorientation=horizontal gt
ltTextView androidid=+idtextbox
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtextAppearance=androidstyleTextAppearanceMedium
androidgravity=center_vertical
androidlayout_gravity=center_vertical
androidlayout_weight=08gt
ltImageView androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidsrc=androiddrawableic_media_playgt
ltLinearLayoutgtgt
ltLinearLayoutgt
723 Custom Adapter
A custom adapter is to be created for the purpose which would bind the array data to the row and
run up to the length of the array implicitly
package comsoulastralcustomlist
import javasecurityProviderService
import androidcontentContext
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetArrayAdapter
import androidwidgetTextView
public class CustomAdapter extends ArrayAdapterltStringgt
Context context
String []objects
int row
public CustomAdapter(Context context int textViewResourceId
String[] objects)
super(context textViewResourceId objects)
thiscontext=context
thisobjects=objects
row=textViewResourceId
TODO Auto-generated constructor stub
Override
public View getView(int position View convertView ViewGroup parent)
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 29
TODO Auto-generated method stub
if(convertView==null)
LayoutInflater
lf=(LayoutInflater)contextgetSystemService(contextLAYOUT_INFLATER_SERVICE)
convertView=lfinflate(Rlayoutrow parent false)
TextView tv=(TextView)convertViewfindViewById(Ridtextbox)
tvsetText(objects[position])
return convertView
724 List Activity
The main list activity which would control the total function
package comsoulastralcustomlist
import androidappActivity
import androidappListActivity
import androidosBundle
import androidwidgetListView
public class CustomListActivity extends ListActivity
static final String[] ACTIVITY_CHOICES = new String[]
Action 1
Action 2
Action 3
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
ListView li=getListView()
CustomAdapter ca=new CustomAdapter(getApplicationContext()
RlayoutrowACTIVITY_CHOICES )
lisetAdapter(ca)
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Navigation 30
73 Listener
To react to selections in the list set an OnItemClickListener to your ListView
lisetOnItemClickListener(new OnItemClickListener()
Override
public void onItemClick(AdapterViewltgt parent View view
int position long id)
ToastmakeText(getApplicationContext()
Click ListItem Number + position ToastLENGTH_LONG)
show()
)
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 31
8 Notification
Several types of situations may arise that require you to notify the user about an event that occurs
in application Some events require the user to respond and others do not For example
When an event such as saving a file is complete a small message should appear to
confirm that the save was successful
If the application is running in the background and needs the users attention the
application should create a notification that allows the user to respond at his or her
convenience
If the application is performing work that the user must wait for (such as loading a file)
the application should show a hovering progress wheel or bar
Each of these notification tasks can be achieved using a different technique
A Toast Notification for brief messages that come from the background
A Status Bar Notification for persistent reminders that come from the background and
request the users response
A Dialog Notification for Activity-related notifications
This document summarizes each of these techniques for notifying the user and includes links to
full documentation
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 32
81 Toast Notification
811 Simple Toast Notification
The default toast notification the code for which is given
below
package comsoulastraltoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidwidgetToast
public class ToastNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Toast toast= ToastmakeText(getApplicationContext() Here is the Toast
NotificationToastLENGTH_LONG )
toastshow()
toastsetGravity(GravityCENTER_HORIZONTAL 0 0)
812 Custom Toast Notification
Steps Involved
Figure 22 S imple Toast Notification
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 33
For a custom toast Notification user must first create a layout for the Toast
Populate the layout with the desired Values
setView for Toast object
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemas
androidcomapkresandroid
androidid=+idcuslay
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=horizontal gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomtoastnotification
import androidappActivity
import androidosBundle
import androidviewGravity
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
import androidwidgetToast
public class CustomToastNotificationActivity extends Activity
Called when the activity is first created
Override
Figure 23 Custom Toast Notification
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 34
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
LayoutInflater inflater=getLayoutInflater()
View layout=inflaterinflate(Rlayoutcustomtoast
(ViewGroup)findViewById(Ridcuslay))
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello This is a custom toast)
Toast toast = new Toast(getApplicationContext())
toastsetGravity(GravityCENTER_VERTICAL 0 0)
toastsetDuration(ToastLENGTH_LONG)
toastsetView(layout)
toastshow()
82 Status Bar Notifications
A status bar notification should be used for any case in
which a background service needs to alert the user
about an event that requires a response A background
service should never launch an activity on its own in
order to receive user interaction The service should
instead create a status bar notification that will launch
the activity when selected by the user
Figure 24 S imple StatusBar Notification
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 35
821 Simple Status Bar Notification
The below code creates a simple status bar notification as shown in figure
package comsoulastralstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
public class StatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
Context context = getApplicationContext()
CharSequence contentTitle = My notification
CharSequence contentText = Hello World
Intent notificationIntent = new Intent(thisSecondclass)
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 36
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationsetLatestEventInfo(context contentTitle contentText
contentIntent)
mNotificationManagernotify(1 notification)
822 Custom Status Bar Notification
Steps Involved
For a custom a statusBar Notification user first create a
layout
Populate the layout with the desired Values
setcontentview for notification object
ltxml version=10 encoding=utf-8gt
ltRelativeLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
androidbackground=6495edgt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_alignParentLeft=true
androidlayout_marginRight=10dp gt
ltTextView androidid=+idtitle
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimagegt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_toRightOf=idimage
androidlayout_below=idtitle gt
ltRelativeLayoutgt
Figure 25 Custom Statusbar
Notification
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 37
package comsoulastralcustomstatusbarnotification
import androidappActivity
import androidappNotification
import androidappNotificationManager
import androidappPendingIntent
import androidcontentContext
import androidcontentIntent
import androidosBundle
import androidwidgetRemoteViews
public class CustomStatusbarNotificationActivity extends Activity
Called when the activity is first created
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
String ns = ContextNOTIFICATION_SERVICE
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns)
int icon = Rdrawableic_launcher
CharSequence tickerText = Hello
long when = SystemcurrentTimeMillis()
Notification notification = new Notification(icon tickerText when)
RemoteViews contentView = new RemoteViews(getPackageName()
Rlayoutcustumlayout)
contentViewsetImageViewResource(Ridimage Rdrawableic_launcher)
contentViewsetTextViewText(Ridtitle Custom notification)
contentViewsetTextViewText(Ridtext This is a custom layout)
notificationcontentView = contentView
Intent notificationIntent = new Intent(this
CustomStatusbarNotificationActivityclass)
PendingIntent contentIntent = PendingIntentgetActivity(this 0
notificationIntent 0)
notificationcontentIntent = contentIntent
mNotificationManagernotify(1 notification)
83 Dialogs
831 Simple Dialogs
In the Activity class after the set content view write the codes given below
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 38
8311 Dialogs with Button
The below code creates a dialog with buttons
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new DialogInterfaceOnClickListener()
public void onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8312 Adding a list
The below code creates a dialog with list
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetItems(items new
DialogInterfaceOnClickListener()
public void
onClick(DialogInterface dialog int item)
ToastmakeText(getApplicationContext() items[item]
ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8313 Adding Radio Buttons
The below code adds radio button to the dialog
Figure 26 Dialog with Button
Figure 27 Dialog with List
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 39
final CharSequence[] items = Red Green
Blue
AlertDialogBuilder builder = new
AlertDialogBuilder(this)
buildersetTitle(Pick a color)
buildersetSingleChoiceItems(items -1
new DialogInterfaceOnClickListener()
public void onClick(DialogInterface
dialog int item)
ToastmakeText(getApplicationContext()
items[item] ToastLENGTH_SHORT)show()
)
AlertDialog alert = buildercreate()
alertshow()
8314 Progress Dialog
The below code adds progress Dialog to the activity
ProgressDialog dialog =
ProgressDialogshow(MyActivitythis
Loading Please wait
true)
8315 Progress Bar
The code displays a progress bar dialog
ProgressDialog progressDialog
progressDialog = new ProgressDialog(mContext)
progressDialogsetProgressStyle(ProgressDialog
STYLE_HORIZONTAL)
progressDialogsetMessage(Loading)
progressDialogsetCancelable(false)
832 Custom Dialogs
Steps Involved
For a custom Dialog user must first create a layout for
the Dialog
Figure 28 Dialog with
Radio Button
Figure 29 Progress Dialog
Figure 30 Progress BarDialog
Figure 31 Custom Dialog
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 40
Populate the layout with the desired Values
setView for dialog
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidid=+idlayout_root
androidorientation=horizontal
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidpadding=10dp
gt
ltImageView androidid=+idimage
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidlayout_marginRight=10dp
gt
ltTextView androidid=+idtext
androidlayout_width=wrap_content
androidlayout_height=fill_parent
androidtextColor=FFF
gt
ltLinearLayoutgt
package comsoulastralcustomdialog
import androidappActivity
import androidappAlertDialog
import androidcontentContext
import androidosBundle
import androidviewLayoutInflater
import androidviewView
import androidviewViewGroup
import androidwidgetImageView
import androidwidgetTextView
public class CustomDialogActivity extends Activity
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Notification 41
Called when the activity is first created
AlertDialogBuilder builder
AlertDialog alertDialog
Override
public void onCreate(Bundle savedInstanceState)
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
Context mContext = getApplicationContext()
LayoutInflater inflater = (LayoutInflater)
mContextgetSystemService(LAYOUT_INFLATER_SERVICE)
View layout = inflaterinflate(Rlayoutcustomlayout(ViewGroup)
findViewById(Ridlayout_root))
TextView text = (TextView) layoutfindViewById(Ridtext)
textsetText(Hello this is a custom dialog)
ImageView image = (ImageView) layoutfindViewById(Ridimage)
imagesetImageResource(Rdrawableic_launcher)
builder = new AlertDialogBuilder(mContext)
buildersetView(layout)
alertDialog = buildercreate()
alertDialogshow()
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 42
9 Storage Based Application Development
Storing data is one of the most important component of each and every application as each
application requires the data to be saved for further use
Android handset provides following storage techniques
Shared Preferences
Internal Storage
External Storage
SQLite Databases
Network Connection
We will use a common layout for all the data storage technique mentioned above
Figure 32 Storage Techniques
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 43
Here is the XML lines of code for the upper layout
ltxml version=10 encoding=utf-8gt
ltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid
androidlayout_width=fill_parent
androidlayout_height=fill_parent
androidorientation=vertical gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Writing to Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idtext
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03gt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Write
androidonClick=writefunc
gt
ltTextView
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieved from Storage
androidtextAppearance=androidstyleTextAppearanceMediumgt
ltEditText
androidid=+idretrieve
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidlayout_weight=03
androideditable=falsegt
ltButton
androidlayout_width=fill_parent
androidlayout_height=wrap_content
androidtext=Retrieve
androidonClick=retrievefunc
gt
ltLinearLayoutgt
User writes in First EditText and presses ―Write button which is then stored using some data
storage technique illustrated below
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 44
91 Shared Preferences
To get a SharedPreferences object for your application use one of two methods
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 dont supply a name
911 Writting to SharedPreference
To write values
Call edit() to get a SharedPreferencesEditor
Add values with methods such as putBoolean() and putString()
Commit the new values with commit()
public void writefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
SharedPreferencesEditor editor = settingsedit()
editorputString(text textgetText()toString())
editorcommit()
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 45
912 Retrieving Shared preferences
To read values use SharedPreferences methods such as getBoolean() and getString()
public void retrievefunc(View v)
SharedPreferences settings = getSharedPreferences(Mypref 0)
String temp=settingsgetString(text Unable to retrieve)
retrievesetText(temp)
92 Internal Storage
You can save files directly on the devices internal storage By default files saved to the internal
storage are private to your application and other applications cannot access them (nor can the
user) When the user uninstalls your application these files are removed
921 Writing to Internal Storage
To create and write a private file to the internal storage
1 Call openFileOutput() with the name of the file and the operating mode This returns a
FileOutputStream
2 Write to the file with write()
3 Close the stream with close()
public void writefunc(View v)
String string = textgetText()toString()
try
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 46
FileOutputStream fos = openFileOutput(FILENAME
ContextMODE_PRIVATE)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to
your application Other modes available are MODE_APPENDMODE_WORLD_READABLE
and MODE_WORLD_WRITEABLE
922 Retrieving from Internal Storage
To read a file from internal storage
Call openFileInput() and pass it the name of the file to read This returns a FileInputStream
Read bytes from the file with read()
Then close the stream with close()
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
FileInputStream fos = openFileInput(FILENAME)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 47
93 External Storage
Every Android-compatible device supports a shared external storage that you can use to save
files This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage Files saved to the external storage are world-readable and can be modified by the user
when they enable USB mass storage to transfer files on a computer
931 Writing to External Storage
The below method writes to External Storage
public void writefunc(View v)
String string = textgetText()toString()
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() + dir)
dirmkdirs()
File file = new File(dir test)
FileOutputStream fos = new FileOutputStream(file)
foswrite(stringgetBytes())
fosclose()
catch (Exception e)
TODO handle exception
ToastmakeText(getApplicationContext() Written
ToastLENGTH_LONG)show()
932 Retrieving from External Storage
The below code reads from the external Storage
public void retrievefunc(View v)
String temp
byte[] buffer=new byte[10]
try
File sdCard = EnvironmentgetExternalStorageDirectory()
File dir = new File (sdCardgetAbsolutePath() +
dirtest)
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 48
FileInputStream fos = new FileInputStream(dir)
fosread(buffer)
fosclose()
catch (Exception e)
TODO handle exception
temp=new String(buffer)
retrievesetText(temp)
The below line must be added to the manifest file for the application to work
ltuses-permission androidname=androidpermissionWRITE_EXTERNAL_STORAGE gt
94 SQLite Database
Android provides full support for SQLite databases Any databases you create will be accessible
by name to any class in the application but not outside the application
First a class needs to be created which extends SQLiteOpenHelper This class on call from
activity creates database and its schema
public class MyDbHelper extends SQLiteOpenHelper
private static final int DATABASE_VERSION = 1
private static final String DATABASE_NAME = mydbdb
private static final String Names_TABLE_NAME = names
private static final String Names_TABLE_CREATE =CREATE TABLE names(names
TEXT)
MyDbHelper(Context context)
super(context DATABASE_NAME null DATABASE_VERSION)
Override
public void onCreate(SQLiteDatabase db)
dbexecSQL(Names_TABLE_CREATE)
Override
public void onUpgrade(SQLiteDatabase arg0 int arg1 int arg2)
TODO Auto-generated method stub
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 49
The activity then calls this class when creating the object of the class by passing context as the
parameter
941 Get Database
Create object of MyDbHelper class
void getdatabase()
mdb=new MyDbHelper(this)
942 Inserting Data
Insert data in the table
public void writefunc(View v)
try
wdb=mdbgetWritableDatabase()
ContentValues contentValues=new ContentValues()
contentValuesput(names textgetText()toString())
wdbinsert(names nullcontentValues)
ToastmakeText(getApplicationContext()Written
ToastLENGTH_LONG)show()
catch (Exception e)
ToastmakeText(getApplicationContext() egetMessage()
ToastLENGTH_LONG)show()
943 Deleting Data
Deleting data from table
public void deleterecords()
try
wdb=mdbgetWritableDatabase()
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Storage Based Application Development 50
wdbdelete(names names=Akash null)
catch (Exception e)
TODO handle exception
944 Updating Data
Updating table
public void update()
try
wdb=mdbgetWritableDatabase()
ContentValues cv=new ContentValues()
cvput(names Ram)
wdbupdate(namescv names=Akash null)
catch (Exception e)
TODO handle exception
945 Retrieving Data
Retrieving data from table
public void retrievefunc(View v) Select Query
String temp=
rdb=mdbgetReadableDatabase()
Cursor cu=rdbrawQuery(select from names null)
if(cumoveToFirst())
do
String str = cugetString(0)
temp=temp+n+str
while(cumoveToNext())
retrievesetText(temp)
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Multimedia 51
10 Multimedia
The Android multimedia framework includes support for capturing and playing audio video and
images in a variety of common media types so that you can easily integrate them into your
applications You can play audio or video from media files stored in your applications resources
from standalone files in the file system or from a data stream arriving over a network
connection all using the MediaPlayer APIs You can also record audio video and take pictures
using the MediaRecorder and Camera APIs if supported by the device hardware
101 Audio
1011 To Record
MediaRecorder recorder = new
MediaRecorder()recordersetAudioSource(MediaRecorderAudioSourceMIC)
recordersetOutputFormat(MediaRecorderOutputFormatRAW_AMR)
recordersetAudioEncoder(MediaRecorderAudioEncoderAMR_NB)
recordersetOutputFile(path)
recorderprepare()
recorderstart()
1012 To Play
MediaPlayer is the easier way if you just want to play an audio file in the background
somewhere in an application
There are no UI controls here but of course you can use MediaPlayerstop() play()
seekTo() etc
Just bind the needed functions to a button gesture or event
It also throws a lot of exceptions which you need to catch
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Multimedia 52
MediaPlayer mediaPlayer = MediaPlayercreate(context Rrawsound_file_1)
mediaPlayerstart() no need to call prepare() create() does that for you
public void audioPlayer(String path String fileName)
set up MediaPlayer
MediaPlayer mp = new MediaPlayer()
mpsetDataSource(path++fileName) surround with try-catch
mpprepare()
mpstart()
102 Tone Generator
Generates desired tone with given tone type(frequency)
tone = new ToneGenerator(AudioManagerSTREAM_DTMF 100) Create
Tone Generator Object
tonestartTone(int tonetypeint duration in Ms) Start tone with tone
type value and duration
103 Video
1031 To Play Video
VideoViewvideoView=(VideoView)findViewById(RidvideoView)
videoViewsetVideoPath(sdcarddcim100MEDIAVIDEO00013gp)
videoViewstart()
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Mobile Web Apps 53
11 Mobile Web Apps
Mobile web apps provide flexibility and code reusability The web apps made for desktop
application can easily be converted to mobile web apps with minimum efforts in doing the same
Languages HTML CSS JAVASCRIPT JQUERY
Features that mobile apps should have are
Linking with native libraries (Accelerometer camera etc)
UI Look and feel like native application (Buttons Labels etc)
Navigation like native application (Screen sliding orientations etc)
111 Linking with native Libraries
Native controls in the HTML can be implemented using phonegap framework which consists of
a webview which links to all the native phone controls like accelerometer camera compass
location based services and provides the navigator access to the above mentioned controls
112 UI Look and feel like native application
Manually UI look and feel in mobile is controlled using CSS One can manually write
the cascading style sheets(Require a lot of effort to write CSS file that matches the native
look)
Existing One can use existing style sheets like provided by IUI which produces native
type look
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Mobile Web Apps 54
113 Navigation like native application
Manually If the CSS is written manually the button events effects should also be
written by the developer using JavaScript and Jquery
Existing If the developer is using existing style sheets like provided by IUI the user
also gets the script file which controls the navigation effects and events
114 Advantages
Code Reusability
Code Simplification
115 Disadvantages
Decrease in battery performance due to increased frameworkslayers
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Game Development 55
12 Game Development
Android supports game development as a result of this several games can be found in android
Play Some types of games in the android are
Accelerometer Based Games
Simple Canvas Based Games
3d Games
121 Accelerometer Based Games
Android handsets provide sensors Accelerometer is one such sensor responsible to detect
movements in x y and z directions Accelerometer based games cannot be tested on Android
Emulator
122 Getting Accelerometer Readings
The below code captures the accelerometer readings
import androidappActivity
import androidhardwareSensor
import androidhardwareSensorEvent
import androidhardwareSensorEventListener
import androidhardwareSensorManager
import androidosBundle
import androidwidgetTextView
public class AccelerometerActivity extends Activity implements
SensorEventListener
private SensorManager sensorManager
TextView xCoor yCoor zCoor
Override
public void onCreate(Bundle savedInstanceState)
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Game Development 56
superonCreate(savedInstanceState)
setContentView(Rlayoutmain)
xCoor=(TextView)findViewById(Ridxcoor) create X axis object
yCoor=(TextView)findViewById(Ridycoor) create Y axis object
zCoor=(TextView)findViewById(Ridzcoor) create Z axis object
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE)
sensorManagerregisterListener(this sensorManagergetDefaultSensor(Se
nsorTYPE_ACCELEROMETER)
SensorManagerSENSOR_DELAY_NORMAL)
sensorManagerregisterListener(thissensorManagergetDefaultSensor(SensorTYP
E_LIGHT)
SensorManagerSENSOR_DELAY_NORMAL)
public void onAccuracyChanged(Sensor sensor int accuracy)
public void onSensorChanged(SensorEvent event)
if(eventsensorgetType()==SensorTYPE_ACCELEROMETER)
assign directions
float x=eventvalues[0]
float y=eventvalues[1]
float z=eventvalues[2]
xCoorsetText(X +x)
yCoorsetText(Y +y)
zCoorsetText(Z +z)
123 Building Game
1231 Main Activity class
Create a main activity class
Pass Activity context and sensor manager to the custom view object created
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Game Development 57
Set the content view of activity as the newly created custom view object
1232 Create Custom View
Extend the View in the Custom View which implements SensorEventListener
Register Accelerometer Sensor event Listener
Each view consists of canvas which is used in game developments Drawing in canvas is
carried out using onDraw() method
1233 Creating Stage Screens
Set Static background using setBackgroundResource(Rdrawableimg_name)
Create a stage screens using Gimp
Set the above created (with transparency channel) in the canvas using
bg=BitmapcreateScaledBitmap(bggetWidth()getHeight()true)
canvasdrawBitmap(bg 0 0null)
onSensorChanged()
Is called when there is movements in X Y and Z directions
Update the positions of the x y and z
To bring about changes in canvas call invalidate() method
The program consists of a static sand background drawn on Custom View
The Second image is the spiral image which consists of transparency and spirals
Using the check conditions for transparency the ball movement is controlled
The ball moves in the transparent region and stucks in the any other region which is opaque
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Conclusion ix
Conclusion
My 5 and half months of training at Sevya provided me thorough knowledge of Mobile
Application Development including Blackberry Android and J2ME
It helped me in understanding the complete life cycle of application development which starts
from analytical phase followed by documentation phase and on verification goes to
implementation phase
In my internship I worked in a team with Mr Vineet Agarwal and Mr Kumar Raja Donthamsetti
and developed some applications with reach controls and also some Gaming applications which I always
dreamed off
I got an opportunity to work as a graphic designer for which I used Open Source Gimp I also got
an opportunity to prepare some documentation and user manuals for the ongoing projects of
Sevya
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
References x
References
Android Developers (httpdeveloperandroidcom)
Google (httpgooglecoin)
Wikipedia (httpwwwwikipediaorg)
Mr Narasayya Donepudi(Co-Founder at Sevya Multimedia)
Mr Kumar Raja Donthamsetti (Associate Software Engineer at Sevya Multimedia)
Mr Vineet Agarwal (Software Engineer at Sevya Multimedia)
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency
Android Application Development
Glossary xi
Glossary
Accelerometer Instrument which get acceleration values of all the axes on
movements
Activity A screen for the application
Android An Open source operating system loaded in smart phones
Context Interface to global information about an application environment
Dalvik It runs the executable dex files
Dialog A type of Notification
Implicit Users are not required to define themselves defined by system
Intents Used to call other Activity
Kernel It is responsible for the interaction of hardware and software
Notification A message generated for better user interaction
Sensor Senses some components like temperature location etc
SQLite A powerful and lightweight relational database engine available to
all applications
Tone Generation of sound at some given Frequency