You are on page 1of 77

ANDROID

OVERVIEW

Overview
What is Android?
Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by
Google, and other companies. Android offers a unified approach to application development for
mobile devices which means developers need only develop for Android, and their applications
should be able to run on different devices powered by Android.The first beta version of the
Android Software Development Kit (SDK) was released by Google in 2007 where as the first
commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1
Jelly Bean.Jelly Bean is an incremental update, with the primary aim of improving the user
interface, both in terms of functionality and performance.The source code for Android is available
under free and open source software licenses. Google publishes most of the code under the
Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public
License version 2.

Facts about Android OS


• Android is an Open Source released by Google.
• Android is popular with technology companies which require a ready-made, low-cost and
customizable operating system for high-tech devices.The first commercially available
phone to run Android was the HTC Dream, released on October 22, 2008.

Page | 1
OHA(Open Handset Alliance)

• OHA is a business alliance created for the purpose of developing open mobile device
standards on 6 Nov 2007.
• It is a consortium of 84 firms.
• Member firms include Google, HTC, Sony, Dell, Intel, Motorola, Qualcomm, Texas
Instruments, Samsung Electronics, LG Electronics, T-Mobile, Sprint Corporation, Nvidia,
and Wind River Systems.
Releases of Android

Features of AndroidAndroid is a powerful operating system competing with Apple 4GS and supports
great features. Few of them are listed below:
Feature Description
• Beautiful UI :-Android OS basic screen provides a beautiful and intuitive user interface.
• Connectivity :-GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC
and WiMAX.
• Storage SQLite, a lightweight relational database, is used for data storage purposes.
• Media support H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC
5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP
• Messaging :-SMS and MMS
• Web browser Based on the open-source WebKit layout engine, coupled with Chrome's
V8 JavaScript engine supporting HTML5 and CSS3.Multi-touch Android has native
support for multi-touch which was initially made available in handsetssuch as the HTC
Hero.
• Multi-tasking User can jump from one task to another and same time various application
can runsimultaneously.
• Resizable widgets Widgets are resizable, so users can expand them to show more content
or shrink them to save space
• Multi-Language Supports single direction and bi-directional text.

Page | 3
• GCM Google Cloud Messaging (GCM) is a service that lets developers send short
message data
• to their users on Android devices, without needing a proprietary sync solution.
• Wi-Fi Direct A technology that lets apps discover and pair directly, over a highbandwidth
peer-to-peer connection.
• Android Beam A popular NFC-based technology that lets users instantly share, just by
touching two NFCenabled phones together. Why Android is Important

• Ability to disseminate smartphones all over the planet.


• Very low price with high performance.
• Text messages, calls, and Internet browsers, are the primary features driving this global
access to information.
• The Android app ecosystem is rich and diverse and their usage is changing people’s lives.

Android Applications
Android applications are usually developed in the Java language using the Android Software
Development Kit.Once developed, Android applications can be packaged easily and sold out
either through a store such as Google Play or the Amazon Appstore.Android powers hundreds of
millions of mobile devices in more than 190 countries around the world. It's the largest installed
base of any mobile platform and growing fast. Every day more than 1 million new Android
devices are activated worldwide.This tutorial has been written with an aim to teach you how to
develop and package Android application. We will start from environment setup for Android
application programming and then drill down to look into various aspects of Android applications.
Android Architecture

Linux Kernel
• Interacts with the hardware and contains all the essential hardware drivers.
• Drivers are programs that control and communicate with the hardware.
• Example : Bluetooth. The kernel include a Bluetooth driver to communicate with the
Bluetooth hardware.
Other functions of Linux Kernel
• Hardware Abstraction
• Memory Management Programs
• Security Settings

• Power Management Software

Page | 5
• Other Hardware Drivers (Drivers are programs that control hardware devices.)
• Support for Shared Libraries
• Network Stack
Libraries
• Set of instructions to guide the device in handling different types of data.
• Open source library:
– Surface Manager: composing windows on the screen
– SGL: 2D Graphics
– Open GL|ES: 3D Library
– Media Framework: Supports playbacks and recording of various audio, video and
picture formats.
– Free Type: Font Rendering
– WebKit: Browser Engine
– libc (System C libraries)
– SQLite
– Open SSL Android Runtime

• Android runtime layer includes a set of core Java libraries(build their apps using the Java
programming language) and the Dalvik Virtual Machine.
• Dalvik is open-source software developed by Dan Bornstein.
• DVM responsible for running apps on Android devices.
Features of DVM
• It is a Register based Virtual Machine.
• It is optimized for low memory requirements.
• It has been designed to allow multiple VM instances to run at once.
• Relies on the underlying OS for process isolation, memory management and threading
support.
• Operates on DEX files.
Execution of Java Code
Application Framework
• Provides many higher-level services to applications in the form of Java classes like,
• Activity Manager: Manages the activity life cycle of applications.
• Content Providers: Manage the data sharing between applications.
• Telephony Manager: Manages all voice calls.
• Location Manager: Location management, using GPS or cell tower etc.
Application
• User mostly interact with this layer for basic functionality.
• Some standard application are pre installed with the device like,
– SMS client app
– Dialer
– Web browser
– Contact manager
Android SDK

• Contains the necessary tools to create, compile and package Android applications.
Page | 7
• Android applications is based on the Java programming language.
• SDK Tools is a downloadable component. It includes the complete set of development and
debugging tools for the Android SDK.
Android Debug Bridge
• Adb tool allows you to connect to a virtual or real Android device.
• For the purpose of managing the device or debugging your application.
Android Developer Tools
• Google provide 2 IDEs for developing application:
• Android Developer Tools (ADT) are based on the Eclipse IDE.
• Android Studio an IDE for creating Android applications.
• Both IDEs contain all required functionality to create, compile, debug and deploy Android
applications.
• Also provide Virtual Device for testing.

Environment Setup
You will be glad to know that you can start your Android application development on either of
the following operating systems:

• Microsoft Windows XP or later version.


• Mac OS X 10.5.8 or later version with Intel chip. Linux including GNU C Library 2.7 or
later.
Second point is that all the required tools to develop Android applications are freely available and
can be downloaded from the Web. Following is the list of software's you will need before you start
your Android application programming.
• Java JDK5 or JDK6
• Android SDK
• Eclipse IDE for Java Developers (optional)
• Android Development Tools (ADT) Eclipse Plugin (optional)
Building Blocks and
Creating Android App
Building Blocks
• Activity
• Intent
• Services
• Content Providers
• Broadcast Receivers

Activity
• Activity is represent a single screen.
• A screen with which users can interact in order to do something.

Page | 9
• Each activity can then start another activity in order to perform different actions. Switch
between activities

Intents
• An intent is an abstract description of an operation to be performed.
• It allow you to interact with components from the own and other applications.
• There are 2 types of Intents :
– Implicit Intents
– Explicit Intents
Types of Intents
• Explicit Intents : have specified a component which provides the exact class to be run.
• Implicit Intents : have not specified a component; instead, they must include enough
information for the system to determine which of the available components is best to run
for that intent.
Services
• Perform long-running operations in the background.
• Does not provide a user interface.
• For example, a service might handle network transactions, play music, perform file I/O, or
interact with a content provider, all from the background.
Content Providers
• A content provider manages access to a central repository of data.
• Own UI for working with the data.
• Handles inter-process communication and secure data access.
• Supplies data from one application to others on request. Broadcast Receivers

• A broadcast receiver (short receiver) is an Android component which allows you to


register for system or application events.
• Respond to broadcast messages from other applications or from the system itself.
• All registered receivers for an event will be notified by the Android runtime once this event
happens.
Download and Install ADT Bundle
• To download adt bundle follow the link below :
– https://developer.android.com/sdk/index.html
• Click on Download Eclipse ADT
• Accept the Terms and Conditions with 32/64 bit machine.
• Click on download Eclipse ADT with android SDK for windows button.

First Android App


• Open Adt bundle and launch Eclipse.
• Go to File - > New - > Android Application Project.
• Enter Application Name and rest remain the same.
• Keep clicking on next button and putting everything remain the same.
Directory Structure

Page | 11
• src: User specified java source code files will be available here.
• gen : The gen directory in an Android project contains auto generated files. R.java contains
the references to certain resources of the project.
• assets : This is empty. You can use it to store raw asset files.
• res: Android supports resources like images and certain XML configuration files, these can
be keep separate from the source code.
• anim: For XML files that are compiled into animation objects.
• layout: UI screen layouts go in the /res/layout folder, which holds XML files containing UI
layout definitions written in XML.
• drawable-hdpi: hd images(png,jpeg) usually 800 by 480pixels.
• drawable-ldpi: low-resolution images usually 320 by 240 pixels.
• drawable-mdpi: medium-resolution images usually 480 by 320 pixels.
• drawable-xhdpi: extra-high-resolution images usually 1,280 by 720 pixels or HD.
• values: XML files that define constant values are in the res/values folder.
• menu: XML files defining menu layouts are in the res/menu folder.
• colors.xml: An XML file that will define the color values to be used in the app.
• dimens.xml: An XML file that defines dimension values, such as standard heights and font
sizes for your UI.
• arrays.xml: An XML file that defines a series of values to be used together
• strings.xml: An XML file that defines text strings to be used in the application
• styles.xml: An XML file that defines styles to be used in the application
• AndroidManifest.xml : it describes certain qualities about the activities, services, intent
receivers, and content providers; what permissions are requested; what external libraries are
needed; what device features are required, what API Levels are supported or required; and
others.
• ic_launcher-web.png : This is an icon to be used in Google play.

Manifest File
It names the Java package for the application.
• Basic building blocks of application like activities, services and etc.
• It determines which processes will host application components.
• Details about permissions.
• Set of classes needed before launch. Elements of Manifest file • <manifest>
– manifest is the root element of the AndroidManifest.xml file.
– package attribute that describes the package name of the activity class.
– versionCode an internal version number. It used only to determine whether one
version is more recent than another.
– versionName the version number shown to users. This attribute can be set as a raw
string or as a reference to a string resource.
• <uses-sdk>

– specifies the platform compatibility of the application.


– minSdkVersion an integer designating the minimum API Level required for the
application to run.
– If not provided,the system assumes a default value of "1“ ie compatible with all
versions of android.
– targetSdkVersion An integer designating the API Level that the application
targets. If not set, the default value equals that given to minSdkVersion.

• <application>
– The declaration of the application.
– Allowbackup whether to allow the application to participate in the backup and
restore infrastructure. If false, no backup or restore of the application will ever be
performed.
– icon an icon for the application as whole, and the default icon for each of the
application's components.
– label a user-readable label for the application as a whole, and a default label for
each of the application's components.
– logo a logo for the application as whole, and the default logo for activities.
– name the fully qualified name of an Application subclass implemented for the
application.
– theme a reference to a style resource defining a default theme for all activities in the
application.
– Individual activities can override the default by setting their own theme attributes.
• <activity>
– Declares an activity that implements part of the application's visual user interface.

Page | 13
– label a user-readable label for the activity.
– name the name of the class that implements the activity, a subclass of Activity.
– screenOrientation the orientation of the activity's display on the device. Eg:
landscape, portrait, behind etc.
• <intent-filters>
– Specifies the types of intents that an activity, service, or broadcast receiver can
respond to.
– An intent filter declares the capabilities of its parent component — what an activity
or service can do and what types of broadcasts a receiver can handle.
– Action adds an action to an intent filter
– Category adds a category name to an intent filter.
– Eg: CATEGORY_DEFAULT, CATEGORY_LAUNCHER
Android Virtual Device
• Open Eclipse IDE, go to windows – > Android Virtual device manager.
• Click on new Button.
• Enter AVD name, choose device you want to run on, select target API level, keep
everything as same.
• Click on OK.
• Choose your created AVD and click on start button and launch. Emulator

AVD Manager
• The AVD Manager provides a graphical user interface in which you can create and manage
Android Virtual Devices (AVDs), which are required by the Android Emulator.
• Android Emulator is used to run, debug and test the android application. If you don't have
the real device, it can be the best way to run, debug and test the application Running your
app

• In order to launch your application on emulator follow the simple step :

• Right click on the project.


• Choose Run As.
• Android Application.
• Emulator will launch and output will display on screen.
Output on Emulator

Page | 15
Activity and
Multimedia
What is Activity
• An activity is a single, focused thing that the user can do.
• An Android application can have several activities.
• One activity in an application is specified as the "main" activity which is presented when
application launches.
• Eg: send an email, a list of new emails or view a map, home screen, login screen etc.

Activity Life Cycle


Phases of Life Cycle
• Active or Running : If an activity in the foreground of the screen.
• Paused: If an activity has lost focus but is still visible.
• Stopped: If an activity is completely obscured by another activity.
• Destroyed: If an activity is no longer in the memory or killed.
Methods of Life Cycle
• onCreate() Called when the activity is first created.
• onStart() Called when the activity is becoming visible to the user.
• onResume() Called when the activity will start interacting with the user, always followed
by onPause().
• onRestart() Called after your activity has been stopped, always followed by onStart().
• onPause() Called when the system is about to start resuming a previous activity.
• onStop() Called when the activity is no longer visible to the user.
• onDestroy() The final call you receive before your activity is destroyed. View

• Every item in a UI is a view.


• Also a subclass of Android View class.
• Android SDK provides many pre-built views for UI.
• Eg: Button, CheckBox, ProgressBar and TextView classes.
• They are also referred as widgets.
ViewGroup
Page | 17
• A view can also be comprised of multiple other views.
• A ViewGroup is a special view that can contain other views.

Layout
• A visual structure for a user interface, such as the UI for an activity or app widget.
• 2 ways to declare layout:
– Declare UI elements in XML – Instantiate layout elements at runtime

• 5 different layouts are:


– Linear Layout - Grid View
– Relative Layout - List View
– Table Layout
LinearLayout
• All the elements are displayed in a linear fashion.
• They are arranged either horizontally or vertically.
• Property used is, android:orientation .
• Eg:
– <LinearLayout android:orientation="vertical"> .
– ... </LinearLayout>
– <LinearLayout android:orientation="horizontal"> .... </LinearLayout>
RelativeLayout
• Every element arranges itself relative to other elements or a parent element.
• Properties of views are defined relatively to other views.
• Eg.:
<Button android:id="@+id/btnLogin" ..></Button>
<Button android:layout_toRightOf="@id/btnLogin“
android:layout_alignTop="@id/btnLogin" ..>

</Button>

Page | 19
TableLayout
• It works in the same way HTML table layouts work.
• We divide the layouts into rows and columns.
• Views in one row are placed under <TableRow>.
• Eg:
<TableRow>
<TextView …. ></ TextView >
<Button ….></Button>
</TableRow>
ListView
• In ListView items or elements are appear in a form List.
• We can select a item in a list and perform necessary actions.
• Eg:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listview" android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Page | 21
GridView
• When we want show data in grid layout like displaying images or icons.
• Elements are displayed in Grid manner.
• Eg: <GridView xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width="fill_parent” android:layout_height="fill_parent“
android:numColumns="auto_fit“/>
Intents
• Intention to do something or an operation to be performed.
• The Intent describes the activity to start and carries any necessary data.
• Glue between activities.
Types of Intent
• Explicit intents specify the component to start by name (the fully-qualified class name).
For example, start a new activity in response to a user action.
• Implicit intents declare a general action to perform, which allows a component from
another app to handle it.
For example, if you want to show the user a location on a map
Switch between Activities
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
startActivity(i);
Example Of Implicit Intents

Page | 23
• Tells the Android system to view a webpage.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(i);

• Android system searches for all components which are registered for the specific action
and the fitting data type.
startActivityForResult
• When we want to get a result back from an activity when it ends.
• For eg, you may start an activity that lets the user pick a person in a list of contacts; when
it ends, it returns the person that was selected.
• startActivityForResult(Intent, int) second integer parameter identifying the call.
• The result will come back through your onActivityResult(int, int, Intent) method. Media
Player

• MediaPlayer class is used to access built-in mediaplayer services like playing audio,video
etc.
• To use MediaPlayer class call the static create method.
– MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

Start stop audio


• To start and stop audio, call the following methods,
– mediaPlayer.start();
– mediaPlayer.pause();
• To start music from the beginning, call reset() method.
– mediaPlayer.reset();
VideoView
• VideoView class is used to play the video files.

• MediaController is a controller for Media Player such as functions like Play/Pause,


Rewind, Fast Forward and a progress slider.
• setMediaController(MediaController controller) sets the media controller to the video
view.
• setVideoURI (Uri uri) sets the URI of the video file
Menus
• It’s a UI entity which provides some action options for a particular view.
• We can create 3 kinds of menus,
– Option Menu
– Context Menu
– Popup Menu

Page | 25
Animation and
Toast Notification
Services
• Toast is a notification message that pop up.
• Display for a certain amount of time.
• Automatically fades out.
• Mostly used for debugging purpose.
– Toast.makeText(getApplicationContext(), "msg msg",
Toast.LENGTH_SHORT).show();
– Toast.makeText(getApplicationContext(), "msg msg",
Toast.LENGTH_LONG).show();

Custom Toast
• When the simple text is not enough.
• We can customize the given Toast View.

Page | 27
• LayoutInflator class is used to inflate the layout from XML using, inflate(int,
ViewGroup).
• Call setView(View) and pass it the inflated layout.

Animation
• Android Animation enables you to change the object property and behaviour at run time.
• There are 2 kinds of animations,
– Frame Animation
– Tween Animation
• Android Animations are alpha, rotate, translate, custom, scale.

Services
• The components of Android system that run in the background are Service components.
• Activity without user interface.
• Taking care of long running background tasks.
• Unaffected by activity switching.
• It can also provide functionality to other applications.
Services Life Cycle

Lifecycle methods
• onCreate() The system calls this method when the service is first created using
onStartCommand() or onBind().
• onDestroy() The system calls this method when the service is no longer used and is being
destroyed.
Started Service vs. Bound Service
• A service is started when an application component, such as an activity, starts it by calling
startService().
• Once started, a service can run in the background indefinitely, even if the component that
started it is destroyed.
• A service is bound when an application component binds to it by calling bindService().
• A bound service offers a client-server interface that allows components to interact with the
service, send requests, get results, and even do so across processes with interprocess
communication (IPC)

Page | 29
SQLite Database
What is SQLite?
• SQLite is Open Source Relational Database i.e. used to perform database operations on
android devices such as storing , manipulating or retrieving persistent data from the
database.
• Supports SQL syntax , transactions and prepared statements.
• It is embedded in android by default. So , there is no need to perform any database setup or
administration task.

Some facts …
• SQLite implements most of the SQL-92 standard for SQL.
• It has partial support for triggers and allows most complex queries(exception made for
outer joins).
• SQLITE does not implement referential integrity constraints through the foreign key
constraint model.
• SQLite uses a relaxed data typing model.
Instead of assigning a type to an entire column, types are assigned to individual values

SQLite Datatypes
SQLite is weakly typed having following storage types: •
NULL: indicates a NULL value

• INTEGER: used to store an integer, according to the size can be used to store 1,2,3,4,6,8.
• REAL: floating-point
• TEXT: In accordance with string to store
• BLOB: according to the binary value is stored without any change.

Sqlite in Android
• Sqlite comes with all android devices.
• Application database is stored at:
DATA/data/APP_NAME/databases/FILENAME
- DATA is the path which the Environment.getDataDirectory() method returns. -
APP_NAME is your application name.
- FILENAME is the name you specify in your application code for the database.
• Android offers a full SQLite relational database library. Every application can create its
own databases over which it has complete control.
• Two packages:
-android.database : contains all the necessary classes for working with databases.
-android.database.sqlite : contains the SQLite specific classes.

Creating and updating database


• To create and upgrade a database in your Android application you create a subclass of the
SQLiteOpenHelper class.
• In the constructor of your subclass you call the super() method of SQLiteOpenHelper,
specifying the database name and the current database version.
• Override following methods:
- onCreate()
- onUpgrade()
SQLiteOpenHelper
• A helper class to manage database creation and version management.
• You create a subclass implementing onCreate(SQLiteDatabase),
onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this
class takes care of opening the database if it exists, creating it if it does not, and upgrading
it as necessary.
Public Methods

• close()-Close any open database object.


• getDatabaseName()-Return the name of the SQLite database being opened, as given to the
constructor.
• getReadableDatabase()-Create and/or open a database.
• getWritableDatabase()-Create and/or open a database that will be used for reading and
writing.

Page | 31
• onCreate(SQLiteDatabase db)-Called when the database is created for the first time.

• onConfigure(SQLiteDatabase db)-Called when the database connection is being


configured, to enable features such as write-ahead logging or foreign key support.
• onDowngrade(SQLiteDatabase db,int oldversion,int newversion)-Called when the database
needs to be downgraded.
• onOpen(SQLiteDatabase db)-Called when the database has been opened
• onUpgrade(SQLiteDatabase db, int oldversion,int newversion)-Called when the database
needs to be upgraded.
• setWriteAheadLoggingEnabled(boolean Enabled)- Enables or disables the use of
writeahead logging for the database
• Override the following methods to create and update your database:
– -onCreate() - is called by the framework, if the database is accessed but not yet created.
– -onUpgrade() - called, if the database version is increased in your application code. This
method allows you to update an existing database schema or to drop the existing database
and recreate it via the onCreate() method.
• Both methods receive an SQLiteDatabase object as parameter which is the Java
representation of the database.
Sample Code public class DataBaseHelper extends
SQLiteOpenHelper

{
String DATABASE_CREATE = "create table "+"LOGIN"+ "( " +"ID"+" integer
primary key autoincrement,"+ "USERNAME text,PASSWORD text); ";
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int _oldVersion, int _newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
onCreate( db);
}
}
SQLiteDatabase
• SQLiteDatabase is the base class for working with a SQLite database in Android and
provides methods to open, query, update and close the database.
• It provides following methods:
- insert()
- update()
- delete()
- execSQL()
- query()
- rawQuery()
SQLiteDatabase Methods
• Insert()-Convenience method for inserting a row into the database.
public long insert (String table, String nullColumnHack, ContentValues values)
e.g., public void insert(String name, String desc) {

ContentValues contentValue = new ContentValues();


contentValue.put(DBhelper.TODO_SUBJECT, name);
contentValue.put(DBhelper.TODO_DESC, desc); database.insert(DBhelper.TABLE_NAME, null,
contentValue);
}
SQLiteDatabase
• SQLiteDatabase is the base class for working with a SQLite database in Android and
provides methods to open, query, update and close the database.
• It provides following methods:

- insert()
- update()
- delete()
- execSQL()
- query()
- rawQuery()
• Insert()-Convenience method for inserting a row into the database.

Page | 33
public long insert (String table, String nullColumnHack, ContentValues values)
e.g., public void insert(String name, String desc) {

ContentValues contentValue = new ContentValues();


contentValue.put(DBhelper.TODO_SUBJECT, name);
contentValue.put(DBhelper.TODO_DESC, desc); database.insert(DBhelper.TABLE_NAME, null,
contentValue);
}
• Update()-Convenience method for updating rows in the database. public int update
(String table, ContentValues values, String whereClause, String[] whereArgs) e.g.,
public int update(long _id, String name, String desc) {

ContentValues contentValues = new ContentValues();


contentValues.put(DBhelper.TODO_SUBJECT, name);
contentValues.put(DBhelper.TODO_DESC, desc);
int i = database.update(DBhelper.TABLE_NAME, contentValues, DBhelper._ID + " = " +
_id, null); return i;
}
• Delete()-Convenience method for deleting rows in the database.
public int delete (String table, String whereClause, String[] whereArgs)
e.g., public void delete(long _id) { database.delete(DBhelper.TABLE_NAME, DBhelper._ID +
"=" + _id, null);
}
• execSQL()-allows to execute an SQL statement directly.
e.g. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
• query()-provides a structured interface for specifying the SQL query.
e.g. return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, null, null, null, null, null);
• rawQuery()-directly accepts an SQL select statement as input.

e.g. Cursor cursor = getReadableDatabase(). rawQuery("select * from todo where _id = ?",
new String[] { id });
ContentValues
• The object ContentValues allows to define key/values.
• The key represents the table column identifier and the value represents the content for
the table record in this column.
• ContentValues can be used for inserts and updates of database entries. Content Values
Example public void

addContact(Contact contact) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact phone Number

// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection

}
Opening and Closing database
• Open Database
SQLiteDatabase = context.openOrCreateDatabase(dbName,
SQLiteDatabase.OPEN_READWRITE, null);
SQLiteDatabase.openDatabase(fullDbNameIncPath, null,
SQLiteDatabase.OPEN_READWRITE);

• Close Database
SQLiteDatabase.close();
(Using SQLiteOpenHelper)
• Extend SQLiteOpenHelper
Override callback methods as required
• Create an instance of it new YourSQLiteOpenHelper(context, dbName, null, version)
• Create or Open Database
SQLiteDatabase = YourSQLiteOpenHelper.getWritableDatabase();

Page | 35
SQLiteDatabase = YourSQLiteOpenHelper.getReadableDatabase();
Also opens the database - if the database already exists, will open it

• Close Database
YourSQLiteOpenHelper.close()

Cursors
• Android cursors are used to gain (sequential & random) access to tables produced by SQL
select statements.
• Cursors primarily provide one row-at-the-time operations on a table.
• Cursors include several types of operators, among them:
- Positional awareness operators (isFirst(), isLast(), isBeforeFirst(),isAfterLast() ),
- Record Navigation (moveToFirst(), moveToLast(), moveToNext(),moveToPrevious(), move(n)
)
- Field extraction (getInt, getString, getFloat, getBlob, getDate, etc.)
-Schema inspection (getColumnName, getColumnNames, getColumnIndex,getColumnCount,
getCount)
• A query returns a Cursor object.
• A Cursor represents the result of a query and basically points to one row of the query result.
• getCount() : returns Number of rows
• moveToFirst() : moves the cursor to first row of returned result
• moveToNext() : moves the cursor to next row of returned result
• moveToPosition(int position) : moves the cursor to particular row of returned result

Cursor Example 1
• public int GetDeptID(String Dept) {
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(deptTable, new String[]{colDeptID+" as
_id",colDeptName},colDeptName+"=?", new String[]{Dept}, null, null, null);
//Cursor c=db.rawQuery("SELECT "+colDeptID+" as _id FROM "+deptTable+" WHERE
"+colDeptName+"=?", new String []{Dept}); c.moveToFirst();
return c.getInt(c.getColumnIndex("_id"));

}
Cursor Example 2
Cursor c = db.query(tableName, tableColumn, where, whereArgs, groupBy, having, orderBy);
ArrayList<ContentValues> retVal = new ArrayList<ContentValues>(); ContentValues map;
if(c.moveToFirst()) { do {

map = new ContentValues(); DatabaseUtils.cursorRowToContentValues(c,


map);
retVal.add(map);
} while(c.moveToNext());
} c.close();

Example :MySQLiteHelper.java public class


MySQLiteHelper extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "BookDB";

public MySQLiteHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, "+
"author TEXT )";
Page | 37
// create books table
db.execSQL(CREATE_BOOK_TABLE);
}@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older books table if existed
db.execSQL("DROP TABLE IF EXISTS books");

// create fresh books table


this.onCreate(db);

}
/**
* CRUD operations (create "add", read "get", update, delete) book + get all books + delete
all books
*/
// Books table name
private static final String TABLE_BOOKS = "books";

// Books Table Columns names private static final


String KEY_ID = "id"; private static final String
KEY_TITLE = "title"; private static final String KEY_AUTHOR
= "author";

private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};


public void addBook(Book book){
Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TITLE, book.getTitle()); // get title
values.put(KEY_AUTHOR, book.getAuthor()); // get author

// 3. insert
db.insert(TABLE_BOOKS, // table null,
//nullColumnHack values); // key/value -> keys = column names/

values = column values

// 4. close
db.close();

}
public Book getBook(int id){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();

// 2. build query Cursor cursor =

db.query(TABLE_BOOKS, // a. table

COLUMNS, // b. column names


" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having

Page | 39
null, // g. order by null);
// h. limit

// 3. if we got results get the first one


if (cursor != null)
cursor.moveToFirst();

// 4. build book object


Book book = new Book();

book.setId(Integer.parseInt(cursor.getString(0)));
book.setTitle(cursor.getString(1)); book.setAuthor(cursor.getString(2));

Log.d("getBook("+id+")", book.toString());
// 5. return book
return book;
}
// Get All Books public
List<Book> getAllBooks() {

List<Book> books = new LinkedList<Book>();


// 1. build the query
String query = "SELECT * FROM " + TABLE_BOOKS;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build book and add it to list
Book book = null; if (cursor.moveToFirst()) {
do {

book = new Book();


book.setId(Integer.parseInt(cursor.getString(0)));
book.setTitle(cursor.getString(1)); book.setAuthor(cursor.getString(2));

// Add book to books


books.add(book);

} while (cursor.moveToNext());
}
Log.d("getAllBooks()", books.toString());
// return books
return books;

// Updating single book public int


updateBook(Book book) {

// 1. get reference to writable DB


SQLiteDatabase db = this.getWritableDatabase();

// 2. create ContentValues to add key "column"/value


ContentValues values = new ContentValues();
values.put("title", book.getTitle()); // get title
values.put("author", book.getAuthor()); // get author

// 3. updating row
int i = db.update(TABLE_BOOKS, //table
values, // column/value KEY_ID+" =
?", // selections

Page | 41
new String[] { String.valueOf(book.getId()) }); //selection args // 4. close
db.close(); return i;

}
// Deleting single book public void
deleteBook(Book book) {

// 1. get reference to writable DB


SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_BOOKS,
KEY_ID+" = ?",
new String[] { String.valueOf(book.getId()) });
// 3. close
db.close();

Log.d("deleteBook", book.toString());
}
}

// 4. close
db.close(); return

i;

Using MySQLiteHelper in Activity public class


MainActivity extends Activity {

@Override protected void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

MySQLiteHelper db = new MySQLiteHelper(this);


// add Books
db.addBook(new Book("Android Application Development Cookbook", "Wei Meng
Lee"));
db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill
Phillips and Brian Hardy")); db.addBook(new Book("Learn Android App
Development", "Wallace Jackson"));

// get all books

List<Book> list = db.getAllBooks();


// delete one book
db.deleteBook(list.get(0));

// get all books


db.getAllBooks();

}
}

Content Providers
• Content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class.
• Content providers let you centralize content in one place and have many different
applications access it as needed.

Page | 43
• A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider
{
}
Content URIs
• To query a content provider, you specify the query string in the form of a URI which has
following format:
<prefix>://<authority>/<data_type>/<id>
• Here is detail of various parts of the URI:
 prefix :This is always set to content://
 authority: specifies the name of the content provider.
e.g. : contacts, browser and third-party content providers(fully qualified name as
com.alma.statusprovider) etc.
 data_type: indicates the type of data that this particular provider provides. ex, if you are
getting all the contacts from the Contacts content provider, then the data path would be
people and URI would look like this content://contacts/people
 Id: specifies the specific record requested. For example, if you are looking for contact
number 5 in the Contacts content provider then URI would look like
thiscontent://contacts/people/5

Create Content Provider


• Create a Content Provider class that extends the ContentProvider baseclass.
• Define your content provider URI address which will be used to access the content.
• Create your own database to keep the content. Usually, Android uses SQLite database .
When your application is launched, the onCreate() handler of each of its Content Providers
is called on the main application thread.

Implement Content Provider queries to perform different database specific operations.


• Finally register your Content Provider in your acitivity file using <provider> tag. Methods

• onCreate() This method is called when the provider is started.


• query() This method receives a request from a client. The result is returned as a Cursor
object.
• insert()This method inserts a new record into the content provider.
• delete() This method deletes an existing record from the content provider.
• update() This method updates an existing record from the content provider.
• getType() This method returns the MIME type of the data at the given URI. MIME Type
Reference

• Content providers can return standard MIME media types, or custom MIME type strings, or
both.
• MIME types have the format:
type/subtype
• For example, the well-known MIME type text/html has the text type and the html subtype.
• Methods for returning MIME types:
 getType()One of the required methods that you must implement for any provider.
 getStreamTypes()A method that you're expected to implement if your provider offers
files.
MIME Types
• Purpose: Indicate a type of data that a content provider deals with
• Definition: Industry standard way to indicate a particular data format
• Syntax: Two text strings separated by slashes
• First part (category): application, audio, image, text, video, etc
• Second Part (codec): html, css, xml, pdf, rtf, etc.
• Examples: text/htm, application/pdf, image/jpeg, audio/mpeg, etc.

Page | 45
• Android MIME Types (Similar syntax as standard MIME types)
– First Part o Access single items: vnd.android.cursor.item o Access multiple items:
vnd.android.cursor.dir

– Second Part: vnd.yourCompany.type


– Examples: vnd.android.cursor.dir/vnd.google.note or
vnd.android.cursor.item/vnd.google.note
• Specifies the data type an activity can process
– Register in the AndroidManifest.xml file
– Example: "vnd.android.cursor.dir/vnd.google.note" OR
"vnd.android.cursor.dir/vnd.google.note"
• Sample Syntax: vnd.android.cursor.<opt>/vnd.company.type
– vnd: non-standard type (vendor)
– android.cursor: required for ContentProvider Manifest registrations
– item: single record; dir: collection of records
– google: company name
– note: content type
• AndroidManifest.xml registration
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />

Referring to a Content Provider


• URI and URL
– Uniform resource identifier (URI) Identifies the name of a resource, but not
necessarily information regarding its location
– Uniform resource Location (URL) is a URI, that identifies a resource location
– Text usage: URI for content providers; URL for referring to Web locations
• URI of a content provider content://com.company.fooProvider/
content://com.acorns.provider.Lessons/
content://com.google.provider.NotePad/
• Note: Android provided shortcut URIs: contacts for
com.google.android.contacts

Refer to the notes SQLite notes table


content://com.google.provider.NotePad/notes/
• Refer to the tenth note content://com.google.provider/NotePad/notes/10
Register the Provider
<provider android:name="NotePadProvider"
android:authorities="com.google.provider.NotePad" />

<activity android:name="NotesList" android:label="@string/title_notes_list"> <intent-


filter>

<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
</intent-filter><intent-filter>
<action android:name="android.intent.action.GET_CONTENT" />
<data android:mimeType="vnd.android.cursor.item/vnd.google.note" > </intent-filter>
</activity>

A Managed Query in Content Provider //


Specify needed columns string[]
projection = new string[]
{ People._ID, People.NAME, People.NUMBER };
// Specivy URI using static Contacts constants
Uri contactUri = Contacts.People.CONTENT_URI;
// Invoke a content provider query Cursor
cursor = managedQuery( contactUri,
projection, //Which columns to return
null, null, // Selection and WHERE
clauses

Contacts.People.NAME + " ASC"); // Order-by (ascending by name) Navigating through


a cursor

• Manipulate the cursor (row pointer)


– if (cursor.moveToFirst() == false)
– cursor.isBeforeFirst(), cursor.isAfterLast, cursor.isClosed()
– while (cursor.moveToNext()) { /* code here */ }
– for (cursor.moveToFirst(); !cursor.isAfterLast(); cur.moveToNext) { … }
• Get column numbers from names
– int nameColumn = cursor.getColumnIndex(People.NAME);
– int phoneColumn = cursor.getColumnIndex(People.NUMBER);
• Get Data from column
– String name = cursor.getString(nameColumn);
– String number = cursor.getString(phoneColumn);
• Prerequisites: Know column names, data types, column name to index relationship Other
Access Methods

• Add
ContentValues values = new ContentValues();
values.put(BookProviderMetaData.BookTableMetaData.BOOK_NAME, "book1");
BookProviderMetaData class

Content Resolver
URI uri = BookProviderMetaData.BookTableMetaData.CONTENT.URI; Uri
values.put(BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR, "author-1");

ContentResolver resolve = context.getContentResolver();


URI uri = BookProviderMetaData.BookTableMetaData.CONTENT.URI;
Uri inserted = resolve.insert(uri, values);
• Delete: Assume that book Index is pre-defined
ContentResolver resolve = context.getContentResolver();

delURI = uri.withAppendedPath(uri, Integer.toString(bookIndex));


resolve.delete(delUri, null, null);

Count
URI uri = BookProviderMetaData.BookTableMetaData.CONTENT.URI;
Cursor cursor = activity.managedQuery(uri, null, null, null, null);
Int numberOfRecords = cursor.getCount(); cursor.close();

• Definition: A Content Resolver is an Android class that matches the URI to an available
Content Provider that can handle the data
• Purpose: Separate the provider from the data, enabling the possibility of multiple content
providers available to handle the same data types
• Access: Use a collection of method calls to insert, retrieve, delete, update data records
• Example: (insert a new note into the notepad)

ContentResolver resolver = activity.getContentResolver();


Uri newUri = resolver.insert(Notepad.Notes.CONTENT_URI, values);
Store Files in an SQLite Database
1. Create the SQLite table with a column called _data
2. Get a writeable output stream
3. Write the file to the reserved column name _data
I/O Example
//Use a content resolver to insert the record
ContentResolver contentResolver = activity.getContentResolver();
Uri newUri = contentResolver.insert(Notepad.Notes.CONTENT_URI, values);
//Use the content resolver to get an output stream directly

OutputStream outStream = contentResolver().openOutputStream(newUri); DataBase Helper

• Purpose
– Manage database creation and version management
– Responsible for creating and upgrading an SQLite database
– Defer database opening and updating to the first use
– Avoids blocking application startup with compute intensive
database upgrades
– Contains methods for getWritableDatabase and
getReadableDatabase
– Simplifies Content Provider access to files
– Eliminates concern over whether the application was terminated
• Implementation
– Create a class that extends SQLiteOpenHelper
– Override onCreate() and onUpgrade() methods Helper Code
(Two tables: Employees, Department) public class DatabaseHelper extends
SQLiteOpenHelper

{ static final String dbName="demoDB"; static


final String employees="Employees"; static final
String colID="EmployeeID";
static final String colName="EmployeeName";
static final String colAge="Age"; static final String
colDept="Dept"; static final String depts="Department";
static final String colDeptID="DeptID"; static final String
colDeptName="DeptName"; static final String
viewEmps="ViewEmps"; public DatabaseHelper(Context
context) // Constructor

{ super(context, dbName, null /* Extension to cursor class */, 1 /* version */); }

Helper code Example:- public void


onCreate(SQLiteDatabase db)

{ db.execSQL("CREATE TABLE " + "depts +


" (" + colDeptID +" INTEGER PRIMARY KEY , " + colDeptName+ " TEXT)");
db.execSQL("CREATE TABLE "+employees +

" ("+ colID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +


colName + " TEXT, "+ colAge + " Integer, " +

colDept + " INTEGER NOT NULL , FOREIGN KEY ("+ colDept +") REFERENCES "
+
deptTable+" ("+colDeptID+"));");
db.execSQL("CREATE TRIGGER fk_empdept_deptid "+" BEFORE INSERT ON
"+employees+
" FOR EACH ROW BEGIN" + " SELECT CASE WHEN ( (SELECT " + colDeptID + "
FROM " + depts + " WHERE " + colDeptID + "=new." + colDept + " ) IS NULL)" +
" THEN RAISE (ABORT, 'Foreign Key Violation') END;" + " END;");
db.execSQL("CREATE VIEW "+ viewEmps + " AS SELECT " + employees + "." +
colID +

" AS _id," + " " + employees + "." + colName + ", " + employees + "." + colAge + ", " +
depts + "." + colDeptName + "" + " FROM "+ employees + " JOIN " + depts +
54 | P a g e

" ON " + employees +"." + colDept+" =" + depts + "." + colDeptID ); public void
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

{
db.execSQL("DROP TABLE IF EXISTS "+employees);
db.execSQL("DROP TABLE IF EXISTS "+depts);
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger");
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger22");
db.execSQL("DROP TRIGGER IF EXISTS fk_empdept_deptid");
db.execSQL("DROP VIEW IF EXISTS "+viewEmps);
onCreate(db);

}
Using a Database helper
Helper = new Helper(context, Helper.DATABASE_NAME, null, Helper.VERSION);
SQLiteDatabase db = Helper.getWritableDatabase(); // Perform query
Cursor cursor = db.query(Helper.DATABASE_TABLE, result_columns, where,
whereArgs, group, having, order);

SQLiteDatabase db = hoardDBOpenHelper.getWritableDatabase(); // Insert row


db.insert(HoardDBOpenHelper.DATABASE_TABLE, null, newValues); SQLiteDatabase
db = hoardDBOpenHelper.getWritableDatabase(); // Update row
db.update(Helper.DATABASE_TABLE, newValues, where, whereArgs);
SQLiteDatabase db = Helper.getWritableDatabase(); // Delete matching rows
db.delete(Helper.DATABASE_TABLE, where, whereArgs);

Find media titles and albums


String[] projection = { MediaStore.Audio.AudioColumns.ALBUM,
MediaStore.Audio.AudioColumns.TITLE };
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

Cursor cursor = getContentResolver().query(uri, projection, null, null, null); int aX=


cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ALBUM);
int tX = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.TITLE);
String[] result = new String[cursor.getCount()]; while (cursor.moveToNext())

{ String title = cursor.getString(tX), album = cursor.getString(aX);


result[cursor.getPosition()] = title + " (" + album + ")";

}
cursor.close();
Accessing the Contact List int iDCol =

ContactsContract.Contacts.ID; int nameCol =

ContactsContract.Contacts.DISPLAY_NAME;

Uri uri = ContactsContract.Contacts.CONTENT_URI;


String[] projection = { iDCol, nameCol };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int nameIndex = cursor.getColumnIndexOrThrow(nameCol); int idIndex =
cursor.getColumnIndexOrThrow(contactIDCol); String[] result = new

String[cursor.getCount()]; while(cursor.moveToNext())

{ String name = cursor.getString(nameIndex);


String id = cursor.getString(idIndex);
result[cursor.getPosition()] = name + " (" + id + ")";

}
cursor.close();
56 | P a g e

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

Sr.No. Method & Description

1 float distanceTo(Location dest)

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

2 float getAccuracy()

Get the estimated accuracy of this location, in meters.


3 double getAltitude()

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

4 float getBearing()

Get the bearing, in degrees.

5 double getLatitude()

Get the latitude, in degrees.

6 double getLongitude()

Get the longitude, in degrees.

7 float getSpeed()

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

8 boolean hasAccuracy()

True if this location has an accuracy.

9 boolean hasAltitude()

True if this location has an altitude.


58 | P a g e

10 boolean hasBearing()

True if this location has a bearing.

11 boolean hasSpeed()

True if this location has a speed.

12 void reset()

Clears the contents of the location.

13 void setAccuracy(float accuracy)

Set the estimated accuracy of this location, meters.

14 void setAltitude(double altitude)

Set the altitude, in meters above sea level.

15 void setBearing(float bearing) Set


the bearing, in degrees.

16 void setLatitude(double latitude) Set


the latitude, in degrees.

17 void setLongitude(double longitude)


Set the longitude, in degrees.

18 void setSpeed(float speed)

Set the speed, in meters/second over ground.

19 String toString()

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

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

• GooglePlayServicesClient.ConnectionCallbacks

• GooglePlayServicesClient.OnConnectionFailedListener

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

Sr.No. Callback Methods & Description

1 abstract void onConnected(Bundle connectionHint)

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

2 abstract void onDisconnected()

This callback method is called when the client is disconnected. You will use
disconnect() method to disconnect from the location client.
60 | P a g e

3 abstract void onConnectionFailed(ConnectionResult result)

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

You should create the location client in onCreate() method of your activity class, then connect it
in onStart(), so that Location Services maintains the current location while your activity is fully
visible. You should disconnect the client in onStop() method, so that when your app is not
visible, Location Services is not maintaining the current location. This helps in saving battery
power up-to a large extent.
Get the Updated Location
If you are willing to have location updates, then apart from above mentioned interfaces, you will
need to implement LocationListener interface as well. This interface provide following callback
method, which you need to implement in your activity class −

Sr.No. Callback Method & Description

1 abstract void onLocationChanged(Location location)

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

Location Quality of Service


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

Sr.No. Method & Description


1 setExpirationDuration(long millis)

Set the duration of this request, in milliseconds.

2 setExpirationTime(long millis)

Set the request expiration time, in millisecond since boot.

3 setFastestInterval(long millis)

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

4 setInterval(long millis)

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

5 setNumUpdates(int numUpdates)

Set the number of location updates.

6 setPriority(int priority)

Set the priority of the request.

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

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

Displaying a Location Address


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

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


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

Check following example to have better understanding on how we use AynchTask in any
Android application to get work done in the background without interfering main task.
Example
Following example shows you in practical how to to use Location Services in your app to get the
current location and its equivalent addresses etc.

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

Create the layout of the Main Activity


In this application we want to display the latitude and longitude of the current geoposition, as
well as the location provider that is used. Also, we want to provide a choice to the user in order
to select criteria for the best location provider at each time. The configuration of the layout is
shown below.

Open res/layout/activity_main.xml file, go to the respective xml tab and paste the following.
activity_main.xml:

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

02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03 android:layout_width="match_parent"

04 android:layout_height="match_parent"

05 android:orientation="vertical" >

06
07 <TextView

08 android:id="@+id/textView"

09 android:layout_width="fill_parent"

10 android:layout_height="wrap_content"

11 android:textSize="20dp"

12 android:text="Do you want a fine accuracy or not?" />

13

14 <TextView

15 android:id="@+id/choice"

16 android:layout_width="fill_parent"

17 android:layout_height="wrap_content"

18 android:text="coarse accuracy selected (default)" />

19

20 <CheckBox

21 android:id="@+id/fineAccuracy"

22 android:layout_width="wrap_content"

23 android:layout_height="wrap_content"

24 android:text="fine accuracy" />

25
64 | P a g e

26 <Button

27 android:id="@+id/chooseRadio"

28 style="?android:attr/buttonStyleSmall"

29 android:layout_width="wrap_content"
30 android:layout_height="wrap_content"

31 android:text="OK" />

32

33 <TextView

34 android:id="@+id/prov"

35 android:layout_width="fill_parent"

36 android:layout_height="wrap_content"

37 android:text="No provider selected yet"

38 android:layout_marginTop="10dp"

39 android:textSize="20dp" />

40
41 <TextView

42 android:id="@+id/lat"

43 android:layout_width="fill_parent"

44 android:layout_height="wrap_content"

45 android:layout_marginTop="20dp"

46 android:text="Latitude: -"

47 android:textSize="20dp" />

48

49 <TextView
50 android:id="@+id/lon"

51 android:layout_width="wrap_content"

52 android:layout_height="wrap_content" 53 android:layout_marginTop="10dp"

54 android:text="Longitude: -"

55 android:textSize="20dp" />

56

57 </LinearLayout>

3. Code the Main Activity


In order to have access to android location services, we need a instance of LocationManager . To
do this, the getSystemService(Context.LOCATION_SERVICE) method of our Activity is called.
Also, some Criteria can be defined, so the best LocationProvider would be selected in

each circumstance. In this example, criteria depends on the user’s choice, as you can see in the
code below. In addition, we use getLastKnownLocation(String) method, which returns the last
Location known from the given provider. Location object provide us useful information
about geographic location and help us to specify the current location of the user.
Moreover, in our application we want to handle the movement of the user and show the current
position, so LocationListener is used. LocationManager can request many callbacks of
LocationListener , in order to handle location or provider’s status changes. With the use of
requestLocationUpdates method, we receive the location updates, procuring the current provider
and location listener.

Open src/com.javacodegeeks.android.locationservicetest/MainActivity.java file and paste the


following.

MainActivity.java:
001 package com.javacodegeeks.android.locationservicetest;

002

003 import android.app.Activity;

004 import android.content.Context;

005 import android.content.Intent;


66 | P a g e

006 import android.location.Criteria;


007 import android.location.Location;

008 import android.location.LocationListener;

009 import android.location.LocationManager;

010 import android.os.Bundle;

011 import android.provider.Settings;

012 import android.view.View;

013 import android.view.View.OnClickListener;

014 import android.widget.Button;

015 import android.widget.CheckBox;

016 import android.widget.TextView;

017 import android.widget.Toast;

018

019 public class MainActivity extends Activity {

020 private TextView latitude;


021 private TextView longitude;

022 private TextView choice;

023 private CheckBox fineAcc;

024 private Button choose;

025 private TextView provText;

026 private LocationManager locationManager;

027 private String provider;

028 private MyLocationListener mylistener;

029 private Criteria criteria;


030
031 /** Called when the activity is first created. */

032

033 @Override

034 public void onCreate(Bundle savedInstanceState) {

035 super.onCreate(savedInstanceState);

036 setContentView(R.layout.activity_main);

037 latitude = (TextView) findViewById(R.id.lat);

038 longitude = (TextView) findViewById(R.id.lon);

039 provText = (TextView) findViewById(R.id.prov);

040 choice = (TextView) findViewById(R.id.choice);

041 fineAcc = (CheckBox) findViewById(R.id.fineAccuracy);

042 choose = (Button) findViewById(R.id.chooseRadio);

043

044 // Get the location manager

locationManager = (LocationManager)

045 getSystemService(Context.LOCATION_SERVICE);

046 // Define the criteria how to select the location provider

047 criteria = new Criteria();

048 criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default

049

050 // user defines the criteria

051 choose.setOnClickListener(new OnClickListener() {

052 @Override
68 | P a g e

053 public void onClick(View v) {

054 // TODO Auto-generated method stub

055 if(fineAcc.isChecked()){

056 criteria.setAccuracy(Criteria.ACCURACY_FINE);

057 choice.setText("fine accuracy selected");

058 }else {

059 criteria.setAccuracy(Criteria.ACCURACY_COARSE);

060 choice.setText("coarse accuracy selected");

061 }

062 }

063 });

064 criteria.setCostAllowed(false);

065 // get the best provider depending on the criteria

066 provider = locationManager.getBestProvider(criteria, false);

067

068 // the last known location of this provider

069 Location location = locationManager.getLastKnownLocation(provider); 070 071


mylistener = new MyLocationListener();

072

073 if (location != null) {

074 mylistener.onLocationChanged(location);

075 } else {
076 // leads to the settings because there is no last known location

Intent intent 077


= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
078 startActivity(intent);

079 }

080 // location updates: at least 1 meter and 200millsecs change

081 locationManager.requestLocationUpdates(provider, 200, 1, mylistener);

082 }

083

084 private class MyLocationListener implements LocationListener {

085

086 @Override

087 public void onLocationChanged(Location location) {

088 // Initialize the location fields

089 latitude.setText("Latitude: "+String.valueOf(location.getLatitude()));

090 longitude.setText("Longitude: "+String.valueOf(location.getLongitude())); 091

provText.setText(provider + " provider has been selected.");

092

093 Toast.makeText(MainActivity.this, "Location changed!",

094 Toast.LENGTH_SHORT).show();

095 }

096

097 @Override

098 public void onStatusChanged(String provider, int status, Bundle extras) {


099 Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
70 | P a g e

100 Toast.LENGTH_SHORT).show();

101 }

102

103 @Override

104 public void onProviderEnabled(String provider) {

105 Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",

106 Toast.LENGTH_SHORT).show();

107

108 }

109

110 @Override

111 public void onProviderDisabled(String provider) {

112 Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!", 113

Toast.LENGTH_SHORT).show();

114 }

115 }

116 }
4. Set the Permissions
In order to receive location updates, we should to declare some permissions. As we mentioned, in
our situation we will use the best provider and this means that our application can support both
GPS and Network providers. For this reason ACCESS_FINE_LOCATION is sufficient.
Otherwise, ACCESS_COARSE_LOCATION is suitable for network providers. Open
AndroidManifest.xml file, go to the xml tab and paste the following.

AndroidManifest.xml: view
sourceprint?
01 <?xml version="1.0" encoding="utf-8"?>

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

03 package="com.javacodegeeks.android.locationservicetest"

04 android:versionCode="1"

05 android:versionName="1.0" >

06

07 <uses-sdk

08 android:minSdkVersion="8"

09 android:targetSdkVersion="19" />

10

11 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

12

13 <application

14 android:allowBackup="true"

15 android:icon="@drawable/ic_launcher"

16 android:label="@string/app_name"

17 android:theme="@style/AppTheme" >

18 <activity

19 android:name="com.javacodegeeks.android.locationservicetest.MainActivity"

20 android:label="@string/app_name" >

21 <intent-filter>

22 <action android:name="android.intent.action.MAIN" />


23
72 | P a g e

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

25 </intent-filter>

26 </activity>

27 </application>

28

29 </manifest>
Android Telephony
Custom Dialer

Android TelephonyManager
android.telephony.TelephonyManager class

It provides information about the telephony services such as subscriber id, sim serial number,
phone network type etc.
TelephonyManager Methods getDeviceId()

Returns the unique device ID, for example, the IMEI for
GSM and the MEID or ESN for CDMA phones.
getSimSerialNumber()
74 | P a g e

Returns the serial number of the SIM, if applicable


getSubscriberId()

Returns the unique subscriber ID, for example, the IMSI for a GSM phone.
getSimSerialNumber()

Returns the serial number of the SIM, if applicable


getNetworkCountryIso()
Returns the ISO country code equivalent of the current registered operator's MCC (Mobile
Country Code). getSimCountryIso()

Returns the ISO country code equivalent for the SIM provider's country code.
getDeviceSoftwareVersion()

Returns the software version number for the device, for example, the IMEI/SV for GSM phones.
getVoiceMailNumber()

Returns the voice mail number.


Add Uses-Permission in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Application will be updated on user's devices without
asking them for new permission.

Note:- Do not forget to add Uses-Permission in AndroidManifest.xml


<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Application will be updated on user's devices without
asking them for new permission.

Note:- Do not forget to add Uses-Permission in AndroidManifest.xml


Get the instance of TelephonyManager TelephonyManager tm;
tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVI
CE);
getSystemService() getSystemService returns handle to

system level service

Context
 Context is an interface to global information about the application.
 It allows access to application – specific resources and classes.

Launching The Custom Dialer


Lines of Code To Make A Phone Call
1. String number=disp.getText().toString();
2. Intent callIntent = new Intent(Intent.ACTION_CALL);
3. callIntent.setData(Uri.parse("tel:"+number));
4. startActivity(callIntent);
76 | P a g e

A Uri object is usually used to tell a ContentProvider what we want to access by reference.
Method Uri.parse creates a new Uriobject from a properly formated String.
Android-Manifest
Uses Permission
<uses-permission android:name="android.permission.CALL_PHONE" />
Application will be updated on user's devices without asking them for
new permission.

Intent :- that says to your phone to use your app when need a dialer
1. <intent-filter>
2. <action android:name="android.intent.action.CALL_BUTTON" />
3. <category android:name="android.intent.category.DEFAULT" /> 4.
</intent-filter>
Calls Replacing the Native Dialer Android-Manifest

android.intent.action.CALL_PRIVILEGED when you

making a call from phonebook using following way:

Phone Book->Contact->Long Click


1. <intent-filter>
2. <action android:name="android.intent.action.CALL_PRIVILEGED" />
3. <category android:name="android.intent.category.DEFAULT" /> 4. </intent-filter>

You might also like