Android SM
Android SM
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.
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
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
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:
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
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>
• <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
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.
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
</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);
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.
Page | 31
• onCreate(SQLiteDatabase db)-Called when the database is created for the first time.
{
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) {
- 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) {
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();
// 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 {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "BookDB";
}
/**
* 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";
// 3. insert
db.insert(TABLE_BOOKS, // table null,
//nullColumnHack values); // key/value -> keys = column names/
// 4. close
db.close();
}
public Book getBook(int id){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
db.query(TABLE_BOOKS, // a. table
Page | 39
null, // g. order by null);
// h. limit
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() {
} while (cursor.moveToNext());
}
Log.d("getAllBooks()", books.toString());
// return books
return books;
// 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) {
Log.d("deleteBook", book.toString());
}
}
// 4. close
db.close(); return
i;
}
}
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
• 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
• 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");
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)
• 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
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);
}
cursor.close();
Accessing the Contact List int iDCol =
ContactsContract.Contacts.DISPLAY_NAME;
String[cursor.getCount()]; while(cursor.moveToNext())
}
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:
Returns the approximate distance in meters between this location and the given
location.
2 float getAccuracy()
4 float getBearing()
5 double getLatitude()
6 double getLongitude()
7 float getSpeed()
8 boolean hasAccuracy()
9 boolean hasAltitude()
10 boolean hasBearing()
11 boolean hasSpeed()
12 void reset()
19 String toString()
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 −
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.
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
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 −
This callback method is used for receiving notifications from the LocationClient
when the location has changed.
2 setExpirationTime(long millis)
3 setFastestInterval(long millis)
4 setInterval(long millis)
5 setNumUpdates(int numUpdates)
6 setPriority(int priority)
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.
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.
Open res/layout/activity_main.xml file, go to the respective xml tab and paste the following.
activity_main.xml:
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"
13
14 <TextView
15 android:id="@+id/choice"
16 android:layout_width="fill_parent"
17 android:layout_height="wrap_content"
19
20 <CheckBox
21 android:id="@+id/fineAccuracy"
22 android:layout_width="wrap_content"
23 android:layout_height="wrap_content"
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"
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>
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.
MainActivity.java:
001 package com.javacodegeeks.android.locationservicetest;
002
018
032
033 @Override
035 super.onCreate(savedInstanceState);
036 setContentView(R.layout.activity_main);
043
locationManager = (LocationManager)
045 getSystemService(Context.LOCATION_SERVICE);
049
052 @Override
68 | P a g e
055 if(fineAcc.isChecked()){
056 criteria.setAccuracy(Criteria.ACCURACY_FINE);
058 }else {
059 criteria.setAccuracy(Criteria.ACCURACY_COARSE);
061 }
062 }
063 });
064 criteria.setCostAllowed(false);
067
072
074 mylistener.onLocationChanged(location);
075 } else {
076 // leads to the settings because there is no last known location
079 }
082 }
083
085
086 @Override
092
094 Toast.LENGTH_SHORT).show();
095 }
096
097 @Override
100 Toast.LENGTH_SHORT).show();
101 }
102
103 @Override
106 Toast.LENGTH_SHORT).show();
107
108 }
109
110 @Override
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
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>
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 unique subscriber ID, for example, the IMSI for a GSM phone.
getSimSerialNumber()
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()
Context
Context is an interface to global information about the application.
It allows access to application – specific resources and classes.
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