0% found this document useful (0 votes)
3 views67 pages

Mobile Application Module

The document is a compilation on mobile application development using Android, covering its introduction, architecture, application fundamentals, GUI basics, data storage, and location services. It details the Android operating system features, versions, and the main building blocks of Android applications, including activities, services, and content providers. Additionally, it discusses the Android framework, UI components, and the lifecycle of activities within an application.

Uploaded by

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

Mobile Application Module

The document is a compilation on mobile application development using Android, covering its introduction, architecture, application fundamentals, GUI basics, data storage, and location services. It details the Android operating system features, versions, and the main building blocks of Android applications, including activities, services, and content providers. Additionally, it discusses the Android framework, UI components, and the lifecycle of activities within an application.

Uploaded by

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

Infolink University College

Dilla Campus
Department of Information Technology
Mobile Application Module

Compiled By: Daniel Dufera (Msc)

May, 2023
Dilla ,Ethiopia
i|Page
Table of Contents
CHAPTER ONE ............................................................................................................................. 1

INTRODUCTION TO ANDROID................................................................................................. 1

What is Android? ........................................................................................................................ 1

Android Versions ........................................................................................................................ 1

Features of Android ..................................................................................................................... 2

Architecture of Android .............................................................................................................. 3

1. Linux kernel ..................................................................................................................... 4

2. Native libraries (middleware)........................................................................................... 4

3. Android Runtime .............................................................................................................. 5

4. Android Framework ......................................................................................................... 6

5. Applications ..................................................................................................................... 7

CHAPTER TWO ............................................................................................................................ 8

ANDROID APPLICATION FUNDAMENTALS ......................................................................... 8

Main Building Blocks ................................................................................................................. 8

1. Activities .............................................................................................................................. 8

Making Activities .................................................................................................................... 9

Activity Life Cycle .................................................................................................................. 9

2. Services .............................................................................................................................. 13

Service lifecycle .................................................................................................................... 14

4. Broadcast Receivers ........................................................................................................... 16

5. Content Providers............................................................................................................... 18

6. Intents ................................................................................................................................. 19

ii | P a g e
CHAPTER THREE BASICS OF ANDROID GUI ...................................................................... 22

Views and Layouts .................................................................................................................... 23

Layouts ...................................................................................................................................... 24

1. LinearLayout .................................................................................................................. 24

2. RelativeLayout ............................................................................................................... 26

3. TableLayout ................................................................................................................... 27

4. Views Layout ................................................................................................................. 28

5. List View ........................................................................................................................ 29

6. GridView layout ............................................................................................................. 32

UI Controls ................................................................................................................................ 33

Menu.......................................................................................................................................... 35

Handling click events ................................................................................................................ 38

Dialogs ...................................................................................................................................... 44

Building an Alert Dialog ....................................................................................................... 45

Notifications .............................................................................................................................. 49

Notification Display Elements............................................................................................... 49

Creating a Notification .......................................................................................................... 51

Managing Notifications ............................................................................................................. 51

Toasts ........................................................................................................................................ 52

CHAPTER FOUR DATA STORAGE IN ANDROID APP ....................................................... 54

Files & Preferences: Android Files ........................................................................................... 54

Choosing a Persistent Environment .......................................................................................... 55

SQLite in Android ..................................................................................................................... 56

Creating and updating Database ............................................................................................ 56

Reading or writing mode ....................................................................................................... 56

ii | P a g e
Adding A Database ................................................................................................................ 56

Implementing CRUD ................................................................................................................ 60

CHAPTER FIVE LOCATION AND MAPS ............................................................................... 60

Localization basics .................................................................................................................... 60

Android: Installing Google APIs............................................................................................... 60

Getting a Google Play API Key ................................................................................................ 61

iii | P a g e
CHAPTER ONE

INTRODUCTION TO ANDROID
What is Android?
Android is a software stack for mobile devices that includes an operating system, middleware
(Software that act as a bridge between an operating system or database) and key applications.
Android is a mobile operating system that is based on a modified version of Linux. Android is a
comprehensive open source platform designed for mobile devices.

✓ Comprehensive platform: complete software stack for mobile devices.


✓ Open source: the entire stacks are free to use.

Android is an embedded Operating system (different kind of machine or Hard Ware and Soft
Ware). Android applications are written using the Java framework, but Android is not Java.
Standard Java libraries such as Swing are not supported. Android uses its own [Link] Time
Picker, global positioning. The Android OS is open source, which means developers can view
and use any of the system source code.

The android is a powerful operating system and it supports large number of applications in Smart
phones. These applications are more comfortable and advanced for the users. The hardware that
supports android software is based on ARM architecture platform. The android is an opensource
operating system means that it’s free and any one can use it. The android has got millions of apps
available that can help you managing your life one or other way and it is available low cost in
market at that reasons android is very popular.

The main advantage of adopting Android is that it offers a unified approach to application
development. Developers need only develop for Android, and their applications should be able to
run on numerous different devices, as long as the devices are powered using Android.

Android Versions
Android has gone through quite a number of updates since its first release. Table below shows
the various versions of Android and their codenames.

1|Page
Table 1.1 Android versions

In February 2011, Google released Android 3.0, a tablet-only release supporting widescreen
devices.

The key changes in Android 3.0 are as follows.

✓ New user interface optimized for tablets


✓ 3D desktop with new widgets
✓ Refined multi-tasking
✓ New web browser features, such as tabbed browsing, form auto-fill, bookmark
synchronization, and private browsing
✓ Support for multi-core processors.

Features of Android
Because Android is open source and freely available to manufacturers for customization, there
are no fixed hardware or software configurations. However, Android itself supports the
following features:

✓ Storage — Uses SQLite, a lightweight relational database, for data storage.

2|Page
✓ Connectivity — Supports GSM/EDGE, IDEN, CDMA, EV-DO, UMTS,
Bluetooth (includes A2DP and AVRCP), Wi-Fi, LTE, and WiMAX.
✓ Messaging — Supports both SMS and MMS.
✓ Web browser — Based on the open source WebKit, together with Chrome’s V8
JavaScript engine
✓ Media support — Includes support for the following media: H.263, H.264 (in 3GP or
MP4 container), MPEG-4 SP, AMR, AMR-WB (in 3GP container), AAC, HE-AAC (in
MP4 or 3GP container), MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.
✓ Hardware support — Accelerometer Sensor, Camera, Digital Compass,
Proximity Sensor, and GPS
✓ Multi-touch — Supports multi-touch screens
✓ Multi-tasking — Supports multi-tasking applications
✓ Flash support — Android 2.3 supports Flash 10.1.
✓ Tethering — Supports sharing of Internet connections as a wired/wireless hotspot.

Architecture of Android
The Android operating system is built on top of a modified Linux kernel. The software stack
contains Java applications running on top of a virtual machine. Components of the system are
written in Java, C, C++, and XML. Android operating system is a stack of software components
which is roughly divided into five sections:

1. Linux kernel
2. Native libraries (middleware)
3. Android Runtime
4. Application Framework
5. Applications

3|Page
Figure 1.1 Android Architecture

1. Linux kernel

It is the heart of android architecture that exists at the root of android architecture. Linux
kernel is responsible for device drivers, power management, memory management, device
management and resource access. This layer is the foundation of the Android Platform.

✓ It contains all low level drivers for various hardware components support.
✓ Android Runtime relies on Linux Kernel for core system services like,
✓ Memory, process management, threading etc.
✓ Network stack
✓ Driver model
✓ Security and more.

2. Native libraries (middleware)


On top of Linux kernel there is a set of libraries including open-source Web browser engine,
WebKit, well known library libc, SQLite database which is a useful repository for storage and

4|Page
sharing of application data, libraries to play and record audio and video, SSL libraries
responsible for Internet security etc.

✓ SQLite Library used for data storage and light in terms of mobile memory footprints and
task execution.
✓ WebKit Library mainly provides Web Browsing engine and a lot more related features.
✓ The surface manager library is responsible for rendering windows and drawing surfaces
of various apps on the screen. The media framework library provides media codecs for
audio and video.
✓ The OpenGl (Open Graphics Library) and SGL(Scalable Graphics Library) are the
graphics libraries for 3D and 2D rendering, respectively.
✓ The FreeType Library is used for rendering fonts.

3. Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile devices.
It consumes less memory and provides fast performance. The Dalvik VM makes use of Linux
core features like memory management and multi-threading, which is intrinsic in the Java
language. The Dalvik VM enables every Android application to run in its own process, with its
own instance of the Dalvik virtual machine.

Dalvik is a specialized virtual machine designed specifically for Android and optimized for
battery-powered mobile devices with limited memory and CPU. Android apps execute on Dalvik
VM, a “clean-room” implementation of JVM Dalvik optimized for efficient execution. Dalvik:
register-based VM, unlike Oracle’s stack-based JVM. Java .class bytecode translated to Dalvik
EXecutable (DEX) bytecode, which Dalvik interprets.

5|Page
Figure. Dalvik Structure.

4. Android Framework
On the top of Native libraries and android runtime, there is android framework. Android
framework includes Android API's such as UI (User Interface), telephony, resources, locations,
Content Providers (data) and package managers. It provides a lot of classes and interfaces for
android application development.

✓ Activity Manager: manages the life cycle of an applications and maintains the back
stack as well so that the applications running on different processes has smooth
navigations.
✓ Package Manager: keeps track of which applications are installed in your device.
✓ Window Manager: Manages windows which are java programming abstractions on top
of lower level surfaces provided by surface manager.
✓ Telephony Managers: manages the API which is used to build the phone applications.

6|Page
✓ Content Providers: Provide feature where one application can share the data with
another application. like phone number, address, etc
✓ View Manager : Buttons , Edit text , all the building blocks of UI, event dispatching etc.

5. Applications
On the top of android framework, there are applications. All applications such as home, contact,
settings, games, browsers are using android framework that uses android runtime and libraries.
Android runtime and native libraries are using linux kernel. Any applications that you write are
located at this layer.

7|Page
CHAPTER TWO
ANDROID APPLICATION FUNDAMENTALS
Main Building Blocks
By “main building blocks,” we refer to the pieces of an application that Android offers you to put
together into an Android app. When you start thinking about your application, it is good to take a
top-down approach. For instance, most programmers design applications in terms of screens,
features, and the interactions between them. You start with a conceptual drawing, something that
you can represent in terms of “lines and circles.” This approach to application development helps
you see the big picture how the components fit together and how it all makes sense. You should
conceptually know when you’d use what component. You will also see how these components
relate to a real-world application.

Figure 2.1 Basic component of Android

1. Activities
An activity is usually a single screen that the user sees on the device at one time. An application
typically has multiple activities, and the user flips back and forth among them.

8|Page
Making Activities
Create subclassing (extending) the framework’s Activity class. Use inheritance to make a
specialized type of Activity (similar to extending JFrame in Swing apps). By extending this class
we inherit all of the methods that are needed to control how the Android OS interacts with the
Activity.
Subclasses AppCompatActivity or Activity
AppCompatActivity is Activity that provides an Action Bar (the toolbar at the top of the screen
with the name of you app). If you change the class to just extend Activity, that bar disappears.

Activity Life Cycle


The activity life cycle is managed by the Activity Manager, a service that runs inside the
Android Framework layer of the stack. The Activity Manager is responsible for creating,

9|Page
destroying, and managing activities. Later, when the user switches screens, the Activity Manager
will move that previous activity to a holding place.

States That an activity can go through

✓ Starting
✓ Running
✓ Stopped
✓ Paused
✓ Destroyed

10 | P a g e
✓ onCreate(): called when the Activity is first created/instantiated. This is where you
initialize the UI (e.g., specify the layout to use), similar to what might go in a constructor.
✓ onStart(): called just before the Activity becomes visible to the user.
The difference between onStart() and onCreate() is that onStart() can be called more than
once (e.g., if you leave the Activity, thereby hiding it, and come back later to make it
visible again).
✓ onResume(): called just before user interaction starts, indicating that the Activity is
ready to be used! This is a little bit like when that Activity “has focus”.
While onStart() is called when the Activity becomes visible, onResume() is called when
then it is ready for interaction. It is possible for an Activity to be visible but not
interactive, such as if there is a modal pop-up in front of it (partially hiding it).
✓ onPause(): called when the system is about to start another Activity (so about to lose
focus). This is the “mirror” of onResume(). When paused, the activity stays visible!
This callback is usually used to quickly and temporarily store unsaved changes (like
saving an email draft in memory) or stop animations or video playback. The Activity may
be being left (on its way out), but could just be losing focus.
✓ onStop(): called when the activity is no longer visible. (e.g., another Activity took over,
but this also be because the Activity has been destroyed. This callback is a mirror of
onStart().This callback is where you should persist any state information (e.g., saving the
user’s document or game state). It is intended to do more complex “saving” work than
onPause().
✓ onRestart(): called when the Activity is coming back from a “stopped” state. This event
allows you to run distinct code when the App is being “restarted”, rather than created for
the first time. It is the least commonly used callback.
✓ onDestroy(): called when the Activity is about to be closed. This can happen because the
user ended the application, or (and this is important!) because the OS is trying to save
memory and so kills the App.

11 | P a g e
Starting state

When an activity doesn’t exist in memory, it is in a starting state. As it starts, the activity invokes
a set of callback methods that you as a developer have an opportunity to fill out. These callbacks
include onCreate(), onStart(), and onResume(). Eventually, the activity will be in a running state,
which means that it will be fully displayed on the screen, in focus, waiting for user to interact
with it. Keep in mind that this transition from starting state to running state is one of the most
expensive operations the application will perform in terms of computing time, and this also
directly affects the battery life of the device.

Running state

Only one activity on a device can be in a running state: it’s the one that is currently on the screen
and interacting with the user. We also say this activity is in focus, meaning that all user
interactions—such as typing, touching the screen, and clicking buttons—are handled by this one
activity. The running activity has priority in terms of getting the memory and resources it needs
to run as quickly as possible. This is because Android wants to make sure the running activity is
zippy and responsive to the user.

Paused state

When an activity is not in focus (i.e., not interacting with the user) but still visible on the screen,
we say it’s in a paused state. This is not a typical scenario, because the device’s screen is usually
small, and an activity is either taking up the whole screen or none at all. We often see this case
with dialog boxes that come up in front of an activity, causing it to become paused. All activities
go through a paused state to being stopped. Paused activities still have high priority in terms of
getting memory and other resources. This is because they are visible and cannot be removed
from the screen without making it look very strange to the user. The Activity Manager calls
onPause() when putting your application into the paused state.

Stopped state

When an activity is not visible, but still in memory, we say it’s in a stopped state. A stopped
activity could be brought back to the front to become a running activity again. Or, it could be
destroyed and removed from memory, which is an operating system choice beyond your control.

12 | P a g e
The system keeps activities around in a stopped state because it is likely that the user will still
want to get back to those activities some time soon. Restarting a stopped activity is far cheaper
than starting an activity from scratch. That is because the Activity Manager already has all the
objects loaded in memory and simply has to bring them all up to the foreground. Stopped
activities can be removed from memory at any pointThe Activity Manager calls onStop() when
putting your application into this state, so it is wise in this method to do anything you need in
order to save the state of your app, such as writing data to disk or a database. Next If activity is
long stayed in Stooped state then it will forced to Destroyed state.

Destroyed state

A destroyed activity is no longer in memory. The Activity Manager decided that this activity is
no longer needed and has removed it. Before the activity is destroyed, it can perform certain
actions, such as save any unsaved information. However, there’s no guarantee that your activity
will be destroyed from the destroyed state. It is possible for a stopped activity to be destroyed as
well. For that reason, it is better to do important work, such as saving unsaved data, in the
onStop() rather than the onDestroy() callback.

2. Services
Services are sort of like Activities that don’t have a user interface or user interaction directly tied
to them. Services can be launched by Activities or Applications, but then do their own thing in
the background even after the starting component is closed (this is distinct from ASyncTask,
which had its lifecycle tied to that of its containing Activity). Services run in the background
and don’t have any user interface components. They can perform the same actions as activities,
but without any user interface. Services are useful for actions that you want to perform for a
while, regardless of what is on the [Link] components that typically run in the
background

Some common uses for a Service include:

✓ Downloading or uploading data from/to a network in the background even if the app is
closed
✓ Saving data to a database without crashing if the user leaves the app

13 | P a g e
✓ Running some other kind of long-running, “background” task even after the app is
closed, such as playing music!

Service lifecycle

Just because a service runs in the background doesn’t necessarily mean it runs on a separate
thread. By default, services and activities run on the same main application thread, often called
the UI thread. If a service is doing some processing that takes a while to complete (such as
performing network calls), you would typically invoke a separate thread to run it. Otherwise,
your user interface will run noticeably slower.

No Callback & Description

1 onStartCommand(): The system calls this method when another component, such as an
activity, requests that the service be started, by calling startService(). If you implement this
method, it is your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.

2 onBind():The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must provide an
interface that clients use to communicate with the service, by returning an IBinder object.
You must always implement this method, but if you don't want to allow binding, then you
should return null.

14 | P a g e
3 onUnbind():The system calls this method when all clients have disconnected from a
particular interface published by the service.

4 onRebind():The system calls this method when new clients have connected to the service,
after it had previously been notified that all had disconnected in its onUnbind(Intent).

5 onCreate():The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-up.

6 onDestroy(): The system calls this method when the service is no longer used and is being
destroyed. Your service should implement this to clean up any resources such as threads,
registered listeners, receivers, etc.

Service example.

Steps to creating a service are:

1. Create the Java class representing your service.


2. Register the service in the [Link] file.
3. Start the service.

15 | P a g e
4. Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents. Components designed to
respond to broadcast messages (called Intents). Can receive broadcast messages from the system.
For example when: A new phone call comes in There is change in battery level or cellID, Can
receive messages broadcast by Applications. Apps can also define new broadcast Messages

The receiver is simply dormant code that gets activated by the occurrence of an event to which
the receiver is subscribed. The “event” takes the form of an intent. The system itself broadcasts
events all the time. For example, when an SMS arrives, a call comes in, the battery runs low, or
the system completes booting up, all those events are broadcast, and any number of receivers
could be triggered by them. Broadcast receivers themselves do not have any visual representation
running in memory. But when triggered, they get to execute some code, such as starting an
activity, a service, or something [Link] important steps to make Broadcast Receiver works for
the system broadcasted intents;

✓ Creating the Broadcast Receiver.


✓ Registering Broadcast Receiver

Creating the Broadcast Receiver:

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the


onReceive() method where each message is received as a Intent object parameter.

Registering Broadcast Receiver:

An application listens for specific broadcast intents by registering a broadcast receiver in


[Link] file. Consider we are going to register MyReceiver for system generated
event ACTION_BOOT_COMPLETED which is fired by the system once the Android system

16 | P a g e
has completed the boot process. [Link] Perform a call to someone specified
by the data.

There are several systems generated events defined as final static fields in the Intent class. The
following table lists a few important system events.

17 | P a g e
5. Content Providers
Content providers are interfaces for sharing data between applications. Enables sharing of data
across applications. Address book, photo gallery, etc. Provides CRUD operations. The methods
that content providers use to implement the four critical operations are.

A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. A content provider can use
different ways to store its data and the data can be stored in a database, in files, or even over a
network.

Sometimes it is required to share data across applications. This is where content providers
become very useful. Content providers let you centralize content in one place and have many

18 | P a g e
different applications access it as needed. A content provider behaves like a database where you
can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and
query() methods. In most cases this data is stored in an SQlite database. 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.

Create Content Provider:

✓ create a Content Provider class that extends the ContentProvider base class.
✓ 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 and
framework needs to override onCreate() method which will use SQLite Open Helper
method to create or open the provider's 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 activity file using <provider> tag.

Example: @lab

6. Intents
Intents are messages that are sent among the major building blocks. They trigger an activity to
start up, tell a service to start, stop, or bind to, or are simply broadcasts. Intents are
asynchronous, meaning the code that sends them doesn’t have to wait for them to be completed.
Intents analogy with a website, intents would be the links connecting various Activities together.

Intents are messages used for activating components.

Intent Object;

✓ Helps identify the receiving component()

19 | P a g e
✓ May contain action to be taken and data act on
✓ Serve as notification for a system(eg new call)

There are following two types of intents supported by Android

Implicit Intents:

These intents do not name a target and the field for the component name is left blank. Implicit
intents are often used to activate components in other applications

For example, you may write the following code to view the webpage.

Intent intent=new Intent(Intent.ACTION_VIEW);

[Link]([Link]("[Link]

startActivity(intent);

20 | P a g e
Explicit intent

Explicit intent going to be connected internal world of application, suppose if you wants to
connect one activity to another activity, we can do this quote by explicit intent, below image is
connecting first activity to second activity by clicking button. These intents designate the target
component by its name and they are typically used for application-internal messages - such as an
activity starting a subordinate service or launching a sister activity. For example −

// Explicit Intent by specifying its class name

Intent i = new Intent([Link], [Link]);

// Starts TargetActivity

startActivity(i);

21 | P a g e
CHAPTER THREE
BASICS OF ANDROID GUI
Methods to Create a User Interface

There are two ways to create a user interface (UI) in Android: declaratively and
programmatically. They are quite different but often are used together to get the job done.

1. Declarative User Interface

The declarative approach involves using XML to declare what the UI will look like, similar to
creating a web page using HTML. You write tags and specify elements to appear on your screen.
If you have ever hand coded an HTML page, you did pretty much the same work as creating an
Android screen.

Advantage:

✓ XML is fairly human-readable, and even people who are unfamiliar with the Android
platform and framework can readily determine the intent of the user interface.

Disadvantage

✓ It doesn’t provide a good way of handling user input. That’s where the programmatic
approach comes in.

2. Programmatic User Interface

A programmatic user interface involves writing Java code to develop the UI. If you have ever
done any Java AWT or Java Swing development, Android is pretty much the same in that
respect. It is similar to many UI toolkits in other languages as well.

Basically, if you want to create a button programmatically,

✓ declare the button variable


✓ create an instance of it
✓ add it to a container
✓ and set any button properties that may make sense, such as colour, text, text size,
background, and so on.

22 | P a g e
Everything you can do on declaratively, you can also do programmatically. But Java also allows
you to specify what happens when that button is actually clicked. This is the main advantage of a
programmatic approach to the user interface.

So which approach to use?

The best practice is to use both you’d use XML to declare what the “button” looks like and Java
to specify what it does.

Views and Layouts


Android organizes its UI elements into views and layouts. Everything you see, such as a button,
label, or text box, is a view. Layouts organize views, such as grouping together a button and
label or a group of these elements. Views in Android are sometimes referred to as widgets. A
layout can contain other children. Those children can furthermore be layouts themselves,
allowing for a complex user interface structure (Figure 3-1). A layout is responsible for
allocating space for each child.

23 | P a g e
Layouts
✓ Linear Layout: is a view group that aligns all children in a single direction, vertically or
horizontally.
✓ Relative Layout: is a view group that displays child views in relative positions.
✓ Table Layout: is a view that groups views into rows and columns.
✓ Absolute Layout : enables you to specify the exact location of its children.
✓ Frame Layout: is a placeholder on screen that you can use to display a single view.
✓ List View: is a view group that displays a list of scrollable items.
✓ Grid View: is a ViewGroup that displays items in a two-dimensional, scrollable grid.

1. LinearLayout
LinearLayout is one of the simplest and most common layouts . A Layout that arranges its
children in a single column or a single row. Available space is divided among layout children
The direction of the row
“android:orientation="vertical"”.
You can also specify gravity, which specifies the alignment of all the child elements using XML
android:gravity="center_horizontal“
The default orientation is horizontal.

24 | P a g e
Linear Layout Attributes
Attribute Description
android:id This is the ID which uniquely identifies the layout.

android:baselineAligned This must be a boolean value, either "true" or "false" and prevents the
layout from aligning its children's baselines.
android:divider This is drawable to use as a vertical divider between buttons. You use a
color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
android:gravity This specifies how an object should position its content, on both the X and
Y axes. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.
android:orientation This specifies the direction of arrangmet and you will use "horizontal" for a
row, "vertical" for a column. The default is horizontal.

25 | P a g e
2. RelativeLayout
RelativeLayout is a ViewGroup that displays child View elements in relative positions. The
position of a View can be specified as relative to sibling elements (such as to the left-of or below
a given element) or in positions relative to the RelativeLayout area (such as aligned to the
bottom, left of center).

26 | P a g e
3. TableLayout
TableLayout is a ViewGroup that displays child View elements in rows and columns. Has a
structure similar to an HTML table. The TableLayout element is like the HTML
<table> element; TableRow is like a <tr> element
In each cell you can use any kind of View element arranged like columns with horizontal linear
layout.

27 | P a g e
4. Views Layout
Views are building blocks of Activities/UI Textiew, EditText, ListView,
imageView,MapView,WebView…
Views can also create using Programmatic UI layout.

28 | P a g e
5. List View
Android ListView is a view which groups several items and display them in vertical scrollable
list. The list items are automatically inserted to the list using an Adapter that pulls content from a
source such as an array or database. An adapter actually bridges between UI components and the
data source that fill data into UI Component. Adapter can be used to supply the data to like
spinner, list view, grid view etc. The ListView and GridView are subclasses of AdapterView
and they can be populated by binding them to an Adapter, which retrieves data from an external
source and creates a View that represents each data entry. The two most common adapters are
ArrayAdapter and SimpleCursorAdapter. We will see separate examples for both the adapters.

ListView Attributes

Attribute Description

android:id This is the ID which uniquely identifies the layout.

android:divider This is drawable or color to draw between list items. .

android:dividerHeight This specifies height of the divider. This could be in px, dp, sp,
in, or mm.

android:entries Specifies the reference to an array resource that will populate


the ListView.

android:footerDividersEnabled When set to false, the ListView will not draw the divider
before each footer view. The default value is true.

android:headerDividersEnabled When set to false, the ListView will not draw the divider after
each header view. The default value is true.

29 | P a g e
ArrayAdapter

You can use this adapter when your data source is an array By default, ArrayAdapter creates a
view for each array item by calling toString() on each item and placing the contents in a
TextView. Consider you have an array of strings you want to display in a ListView, initialize a
new ArrayAdapter using a constructor to specify the layout for each string and the string array:

✓ First argument this is the application context


✓ Second argument will be layout defined in XML file and having TextView for each string
in the array.
✓ Final argument is an array of strings which will be populated in the text view.

[Link]

Once you have array adaptor created, then simply call setAdapter() on your ListView object as
follows:

You will define your list view under res/layout directory in an XML file. For our example we are
going to using activity_main.xml file. Following is the example which will take you through
simple steps to show how to create your own Android application using ListView. Follow the
following steps to modify the Android application we created in Hello World Example:

30 | P a g e
activity_main.xml file

31 | P a g e
activity_listview.xml file

6. GridView layout
Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid
items are not necessarily predetermined. An adapter actually bridges between UI components
and the data source that fill data into UI Component. Adapter can be used to supply the data to
like spinner, list view, grid view etc. The ListView and GridView are subclasses of AdapterView
and they can be populated by binding them to an Adapter, which retrieves data from an external
source and creates a View that represents each data entry. They automatically inserted to the
layout using a ListAdapter.

GridView Attributes

android:id This is the ID which uniquely identifies the layout.

32 | P a g e
android:columnWidth This specifies the fixed width for each column. This could be in px,
dp, sp, in, or mm.

android:gravity Specifies the gravity within each cell. Possible values are top,
bottom, left, right, center, center_vertical, center_horizontal etc.

android:horizontalSpacing Defines the default horizontal spacing between columns. This


could be in px, dp, sp, in, or mm.

android:numColumns Defines how many columns to show. May be an integer value, such
as "100" or auto_fit which means display as many columns as
possible to fill the available space.
android:verticalSpacing Defines the default vertical spacing between rows. This could be in
px, dp, sp, in, or mm.

UI Controls
An Android application user interface is everything that the user can see and interact with. A
View is an object that draws something on the screen that the user can interact with and
aViewGroup is an object that holds other View (and ViewGroup) objects in order to define the
layout of the user interface.

Android UI Controls

UI control description

TextView This control is used to display text to the user.

33 | P a g e
EditText EditText is a predefined subclass of TextView that includes rich editing
capabilities.

AutoCompleteTextView The AutoCompleteTextView is a view that is similar to EditText, except that it


shows a list of completion suggestions automatically while the user is typing.

Button A push-button that can be pressed, or clicked, by the user to perform an action.

ImageButton is a button with an image that can be pressed or clicked by the users.

CheckBox An on/off switch that can be toggled by the user. You should use checkboxes
when presenting users with a group of selectable options that are not mutually
exclusive.

ToggleButton An on/off button with a light indicator.

RadioButton The RadioButton has two states: either checked or unchecked.

RadioGroup A RadioGroup is used to group together one or more RadioButtons.

ProgressBar The ProgressBar view provides visual feedback about some ongoing tasks,
such as when you are performing a task in the background.

Spinner A drop-down list that allows users to select one value from a set.

TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour
mode or AM/PM mode.

DatePicker The DatePicker view enables users to select a date of the day.

34 | P a g e
Menu
Appear whenever the user presses the menu button. Useful for giving different options without
leaving the current Activity. Don’t make too big menus, or they’ll cover entirely the Activity. It
has 3 types
✓ Options menu: Is the primary collection of menu items for an activity. It's where you
should place actions that have a global impact on the app, such as "Search," "Compose
email," and "Settings."
✓ Context menu: Is a floating menu that appears when the user performs a long-click on
an element. It provides actions that affect the selected content or context frame.
✓ Popup menu: Displays a list of items in a vertical list that's anchored to the view that
invoked the menu.
Creating a Menu
Two methods (again):
XML
✓ Place a file inside res/menu/
✓ Inflate the menu inside the Activity
✓ Useful if you want to create the same menu inside different activities
Java
✓ Create the menu directly inside the activity
Defining a Menu in XML.
For all menu types, Android provides a standard XML format to define menu items. Define a
menu and all its items in an XML menu resource then inflate the menu resource (load it as
a Menu object) in activity. Using a menu resource is a good practice for a few reasons:

✓ It's easier to visualize the menu structure in XML.


✓ It separates the content for the menu from application's behavioral code.
✓ It allows to create alternative menu configurations for different platform versions, screen
sizes, and other configurations by leveraging the app resources framework.

To define the menu, create an XML file inside project's res/menu/ directory and build the menu
with the following elements:

✓ <menu>: Defines a Menu, which is a container for menu items. A <menu> element must
be the root node for the file and can hold one or more <item> and <group> elements.

35 | P a g e
✓ <item>: Creates a MenuItem, which represents a single item in a menu. It may contain a
nested <menu>element in order to create a submenu.
✓ <group>: An optional, invisible container for <item> elements. It allows you to
categorize menu items so they share properties such as active state and visibility.

The <item> element


The <item> element supports several attributes you can use to define an item's
appearance and behavior.
The items element has the following important attributes:
android:id
✓ A resource ID that's unique to the item, which allows the application can
recognize the item when the user selects it.
android:icon
✓ A reference to a drawable to use as the item's [Link]:title
✓ A reference to a string to use as the item's title.
android:showAsAction
✓ Specifies when and how this item should appear as an action item in the action
bar.

Adding a Sub Menu

You can add a submenu to an item in any menu (except a submenu) by adding
a <menu> element as the child of an <item>. Submenus are useful when your application has a

36 | P a g e
lot of functions that can be organized into topics, like items in a PC application's menu bar (File,
Edit, View, etc.).

For example:

Creating an Options Menu

The options menu is where you should include actions and other options that are relevant to the
current activity context, such as "Search," "Compose email," and "Settings.“ To specify the
options menu for an activity, override onCreateOptionsMenu(). In this method, you can inflate
your menu resource (defined in XML) into the Menu provided in the callback.

For example:

37 | P a g e
Handling click events
When the user selects an item from the options menu (including action items in the action bar),
the system calls your activity's onOptionsItemSelected() method, which passes
the MenuItem selected. You can identify the item by calling getItemId(), which returns the
unique ID for the menu item (defined by the android:id attribute in the menu resource or with an
integer given to the add() method). You can match this ID against known menu items to perform
the appropriate action.

When you successfully handle a menu item, return true. If you don't handle the menu item, you
should call the superclass implementation of onOptionsItemSelected() (the default
implementation returns false).

Creating Contextual Menus

A contextual menu offers actions that affect a specific item or context frame in the UI. You can
provide a context menu for any view, but they are most often used for items in

38 | P a g e
a ListView, GridView, or other view collections in which the user can perform direct actions on
each item.

In a floating context menu. A menu appears as a floating list of menu items (similar to a dialog)
when the user performs a long-click (press and hold) on a view that declares support for a
context menu. Users can perform a contextual action on one item at a time.

Creating a floating context menu

To provide a floating context menu:

✓ Implement the onCreateContextMenu() method in your Activity. When the


registered view receives a long-click event, the system calls
your onCreateContextMenu()method. This is where you define the menu items,
usually by inflating a menu resource.

39 | P a g e
MenuInflater allows you to inflate the context menu from a menu resource. The callback method
parameters include the View that the user selected and a ContextMenu. ContextMenuInfo object
that provides additional information about the item selected. If your activity has several views
that each provide a different context menu, you might use these parameters to determine which
context menu to inflate.

Implement onContextItemSelected( ):

When the user selects a menu item, the system calls this method so you can perform the
appropriate action.

Creating a Popup Menu

A PopupMenu is a modal menu anchored to a View. It appears below the anchor view if there is
room, or above the view otherwise. It's useful for: If you define your menu in XML, here's how
you can show the popup menu: Instantiate a PopupMenu with its constructor, which takes the
current application Context and the View to which the menu should be anchored.
Use MenuInflater to inflate your menu resource into the Menu object returned by using
[Link]() and Call [Link]().

40 | P a g e
To perform an action when the user selects a menu item, you must implement the
[Link] interface and register it with your PopupMenu by calling
setOnMenuItemclickListener(). When the user selects an item, the system calls
the onMenuItemClick() callback in your interface.

41 | P a g e
Creating Menu Groups

A menu group is a collection of menu items that share certain traits.

With a group, you can:

✓ Show or hide all items with setGroupVisible()


✓ Enable or disable all items with setGroupEnabled()
✓ Specify whether all items are checkable with setGroupCheckable()

42 | P a g e
You can create a group by nesting <item> elements inside a <group> element in your menu
resource or by specifying a group ID with the add() method.

Using checkable menu items

A menu can be useful as an interface for turning options on and off, using a checkbox for stand-
alone options, or radio buttons for groups of mutually exclusive options. You can define the
checkable behavior for individual menu items using the android:checkable attribute in
the <item> element, or for an entire group with the android:checkableBehavior attribute in.

The android:checkableBehavior attribute accepts either:

43 | P a g e
Single: Only one item from the group can be checked (radio buttons)

All: All items can be checked (checkboxes)

None: No items are checkable

You can apply a default checked state to an item using the android:checked attribute in
the <item> element and change it in code with the setChecked() method. When a checkable item
is selected, the system calls your respective item-selected callback method (such as
onOptionsItemSelected()). You can query the current state of the item (as it was before the user
selected it) with isChecked() and then set the checked state with setChecked().

Dialogs
A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog does not fill the screen and is normally used for modal events that require
users to take an action before they can proceed.

44 | P a g e
The Dialog class is the base class for dialogs, but you have to use one of the following
subclasses:

✓ AlertDialog: A dialog that can show a title, up to three buttons, a list of selectable items,
or a custom layout.
✓ DatePickerDialog or TimePickerDialog: A dialog with a pre-defined UI that allows the
user to select a date or time.

These classes define the style and structure for your dialog, but you should use
a DialogFragment as a container for your dialog. The DialogFragment class provides all the
controls you need to create your dialog and manage its appearance, instead of calling methods on
the Dialog object. Using DialogFragment to manage the dialog ensures that it correctly handles
lifecycle events such as when the user presses the Back button or rotates the screen.
The DialogFragment class also allows you to reuse the dialog's UI as an embeddable component
in a larger UI.

Building an Alert Dialog


The AlertDialog class allows you to build a variety of dialog designs and is often the only dialog
class you'll need. As shown in figure, there are three regions of an alert dialog:

✓ Title: This is optional and should be used only when the content area is occupied by a
detailed message, a list, or custom layout. If you need to state a simple message or
question, you don't need a title.
✓ Content area: This can display a message, a list, or other custom layout.
✓ Action buttons: There should be no more than three action buttons in a dialog.

45 | P a g e
Creating a Dialog Fragment
You can accomplish a wide variety of dialog designs by extending DialogFragment and
creating a AlertDialog in the onCreateDialog() callback method.

46 | P a g e
Adding buttons.
To add action buttons, call the setPositiveButton() and setNegativeButton() methods:

The set...Button() methods require a title for the button (supplied by a string resource) and a
[Link] that defines the action to take when the user presses the button.

There are three different action buttons you can add:

✓ Positive: You should use this to accept and continue with the action (the "OK"
action).
✓ Negative: You should use this to cancel the action.
✓ Neutral: You should use this when the user may not want to proceed with the
action, but doesn't necessarily want to cancel. It appears between the positive and
negative buttons. For example, the action might be "Remind me later.“

You can add only one of each button type to an AlertDialog. That is, you cannot have more than
one "positive" button.

Adding a list.

There are three kinds of lists available with the AlertDialog APIs:

✓ A traditional single-choice list

47 | P a g e
✓ A persistent single-choice list (radio buttons)
✓ A persistent multiple-choice list (checkboxes)

To create a single-choice list like the one in figure, use the setItems() method:

Dismissing a Dialog.

When the user touches any of the action buttons created with an [Link], the system
dismisses the dialog for [Link] system also dismisses the dialog when the user touches an item
in a dialog list, except when the list uses radio buttons or checkboxes. Otherwise, you can
manually dismiss your dialog by calling dismiss() on your DialogFragment. In case you need to
perform certain actions when the dialog goes away, you can implement the onDismiss() method
in your DialogFragment. You can also cancel a dialog. This is a special event that indicates the
user explicitly left the dialog without completing the task. This occurs if the user presses
the Back button, touches the screen outside the dialog area, or if you explicitly call cancel() on
the Dialog (such as in response to a "Cancel" button in the dialog). As shown in the example

48 | P a g e
above, you can respond to the cancel event by implementing onCancel() in your
DialogFragment class.

Notifications
A notification is a message you can display to the user outside of your application's normal UI.
When you tell the system to issue a notification, it first appears as an icon in the notification area.
To see the details of the notification, the user opens the notification drawer. Both the notification
area and the notification drawer are system-controlled areas that the user can view at any time.

Notification Display Elements


Notifications in the notification drawer can appear in one of two visual styles, depending on the
version and the state of the drawer:

✓ Normal view: The standard view of the notifications in the notification drawer.
✓ Big view: A large view that's visible when the notification is expanded. Big view is part
of the expanded notification feature available as of Android 4.1.

Normal view.

A notification in normal view appears in an area that's up to 64 dp tall. Even if you create a
notification with a big view style, it will appear in normal view until it's expanded. An example
of a normal view:

The callouts in the illustration refer to the following:

✓ Content title
✓ Large icon
✓ Content text

49 | P a g e
✓ Content info
✓ Small icon
✓ Time that the notification was issued.

Big view.

A notification's big view appears only when the notification is expanded, which happens when
the notification is at the top of the notification drawer, or when the user expands the notification
with a gesture. Expanded notifications are available starting with Android 4.1.

The following screenshot shows an inbox-style notification:

Notice that the big view shares most of its visual elements with the normal view. The only
difference is callout number 7, the details area. Each big view style sets this area in a different
way.

The available styles are:

✓ Big picture style: The details area contains a bitmap up to 256 dp tall in its detail section.
✓ Big text style: Displays a large text block in the details section.
✓ Inbox style: Displays lines of text in the details section.

All of the big view styles also have the following content options that aren't available in normal
view:

50 | P a g e
✓ Big content title: Allows you to override the normal view's content title with a title that
appears only in the expanded view.
✓ Summary text: Allows you to add a line of text below the details area.

Creating a Notification
Notification in android are represented by the Notification class. To create notification use
NotificationManager class which can be received from the Context, [Link] activity or a service
,via GetSystemService() method. The [Link] provides an builder interface to create
an Notification object PendingIntent to specify the action which should be performed once the
user select the notification.

Required notification contents

✓ A Notification object must contain the following:


✓ A small icon, set by setSmallIcon()
✓ A title, set by setContentTitle()
✓ Detail text, set by setContentText()

Managing Notifications
When you need to issue a notification multiple times for the same type of event, you should
avoid making a completely new notification. Instead, you should consider updating a previous
notification, either by changing some of its values or by adding to it, or both. For example,

51 | P a g e
Gmail notifies the user that new emails have arrived by increasing its count of unread messages
and by adding a summary of each email to the notification.

Removing notifications.

Notifications remain visible until one of the following happens:

✓ The user dismisses the notification either individually or by using "Clear All" (if the
notification can be cleared).
✓ The user clicks the notification, and you called setAutoCancel() when you created the
notification.
✓ You call cancel() for a specific notification ID. This method also deletes ongoing
notifications.
✓ You call cancelAll(), which removes all of the notifications you previously issued.

Toasts
A toast provides simple feedback about an operation in a small popup. It only fills the amount of
space required for the message and the current activity remains visible and interactive. Toasts
automatically disappear after a timeout. For example, navigating away from an email before you
send it triggers a "Draft saved" toast to let you know that you can continue editing later.

52 | P a g e
The Basics.

First, instantiate a Toast object with one of the makeText() methods.

✓ This method takes three parameters: the application Context, the text message, and the
duration for the toast.
✓ It returns a properly initialized Toast object.

You can display the toast notification with show(), as shown in the following example:

Positioning your Toast.

A standard toast notification appears near the bottom of the screen, centered horizontally. You
can change this position with the setGravity(int, int, int) method. This accepts three parameters:
a Gravity constant, an x-position offset, and a y-position [Link] example, if you decide that
the toast should appear in the top-left corner, you can set the gravity like this:

If you want to nudge the position to the right, increase the value of the second parameter. To
nudge it down, increase the value of the last parameter.

53 | P a g e
CHAPTER FOUR
DATA STORAGE IN ANDROID APP
Files & Preferences: Android Files
Persistence is a strategy that allows the reusing of volatile objects and other data items by storing
them Into a permanent storage system such as disk files and databases. Permanent files can be
stored internally in the device’s main memory (usually small, but not volatile) or externally in
the much larger SD card. Files stored in the device’s memory, share space with other
application’s resources such as code, icons, pictures, music, etc. Internal files are called:
Resource Files or Embedded Files.

Exploring Android’s File System.

54 | P a g e
Choosing a Persistent Environment
Your permanent data storage destination is usually determined by parameters such as: size
(small/large), location (internal/external), accessibility (private/public).

Depending of your situation the following options are available:

✓ Shared Preferences Store private primitive data in key-value pairs.


✓ Internal Storage Store private data on the device’s main memory.
✓ External Storage Store public data on the shared external storage.
✓ SQLite Databases Store structured data in a private/public database.
✓ Network Connection Store data on the web.

Shared Preferences.

SharedPreferences files are good for handling a handful of Items. Data in this type of container is
saved as <Key, Value> pairs where the key is a string and its associated value must be a
primitive data type. Data is stored in the device’s internal main memory. PREFERENCES are
typically used to keep state information and shared data among several activities of an
application.

55 | P a g e
SQLite in Android
SQLite is embedded into every Android device. Using an SQLite database in Android does not
require a setup procedure or administration of the database. You only have to define the SQL
statements for creating and updating the database. Afterwards the database is automatically
managed for you by the Android platform. Reasons why SQLite is a great fit for Android app
development: Zero-Configuration Database: There is no need for an administrator to create a
new database instance or assign access permissions to users. It doesn’t have a server. There’s no
SQLite database process running. It’s open source.

Creating and updating Database


The main package is [Link] that contains the classes to manage your own
databases. To create and upgrade a database in your Android application you create a subclass of
the SQLiteOpenHelper class. In this class you need to override the following methods to create
and update your database.

✓ onCreate() - This method is called only when you create a database for the first time.
✓ onUpgrade() - called, if the database version is increased in your application code.

Reading or writing mode


The SQLiteOpenHelper class provides the getReadableDatabase() and getWriteableDatabase()
methods to get access to an SQLiteDatabase object. getReadableDatabase():Create and/or open a
database (read-only database object will be returned). getWriteableDatabase():Create and/or
open a database that will be used for reading and writing.

Adding A Database
✓ Create a Class that extends SQLiteOpenHelper
✓ Override the Constructor
✓ Override the onCreate and onUpgrade

56 | P a g e
57 | P a g e
Define Fields

Modify Constructor.

58 | P a g e
Code onCreate.

Code onUpgrade.

59 | P a g e
Implementing CRUD
✓ Instantiate the Database Helper Class
✓ Get a Writable / Readable Database
✓ Perform CRUD operations

CHAPTER FIVE
LOCATION AND MAPS
Localization basics
Geolocalization: Identification of the real-world geographic location of an the end-user. location-
based services (LBS): enable you to find the device’s current location.

 LOCALIZATION THROUGH GPS


 LOCALIZATION THROUGH WI-FI
 LOCALIZATION THROUGH CELLULAR NETWORK

How? You can specify which technology to use


✓ explicitly by name
✓ you can provide a set of Criteria in terms of accuracy, cost, and other requirements and
let Android select the most appropriate
Maps and location-based services use latitude and longitude to pinpoint geographic locations, but
your users are more likely to think in terms of a street address. The maps library includes a
geocoder that you can use to convert back and forth between latitude/longitude values and real-
world addresses. Using the external Maps library included as part of the Google API package,
you can create map-based Activities using Google Maps as a user interface element. You have
full access to the map, which enables you to control display settings, alter the zoom level, and
pan to different locations.
Android: Installing Google APIs
STEP -1: Install and Setup Google Play Service SDK

60 | P a g e
Window → Android SDK
Manager
→install packages

Check Google Play and Google


Repository are installed,
or install them otherwise

Getting a Google Play API Key


Note: Existing keys from a Google Maps Android v1 application, commonly known as
MapView, will not work with the v2 API. The Google Maps Android API uses a new system of
managing keys. Note: You need an Android API key, not a browser key. You can use the same
API key for your Google Maps Android API apps and your Google Places API for Android apps.

Access your project's API keys and other credentials as follows:

✓ Go to the Google Developers Console([Link]


✓ In the sidebar on the left, select Credentials.
✓ If your project doesn't already have an Android API key, create one now by selecting
Add credentials > API key > Android key.
✓ In the resulting dialog, enter your app's SHA-1 fingerprint and package name. For ample:
B:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75

[Link]

Your new Android API key appears in the list of API keys for your project. An API key is a
string of characters, something like this:

AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0

61 | P a g e
Add the API key to your application

Follow the steps below to include the API key in your application's manifest, contained in the
file [Link]. In [Link], add the following element as a child of the
application.

Substitute your API key for YOUR_API_KEY in the value attribute. This element sets the key
[Link].API_KEY to the value of your API key. Save [Link] and
re-build your application.

USING LOCATION-BASED SERVICES

“Location-based services” is an umbrella term that describes the different technologies you can
use to find a device’s current location.

The two main LBS elements are:

✓ Location Manager - This class provides access to the system location services. These
services allow applications to obtain periodic updates of the device’s geographical
location, or to fire an application-specified Intent when the device enters the proximity of
a given geographical location.
✓ Location Providers -Each of these represents a different location-fi nding technology
used to determine the device’s current location.

Using the Location Manager, you can do the following:

✓ Obtain your current location


✓ Follow movement
✓ Set proximity alerts for detecting movement into and out of a specified area
✓ Find available Location Providers
✓ Monitor the status of the GPS receiver

62 | P a g e
SELECTING A LOCATION PROVIDER

Depending on the device, you can use several technologies to determine the current location.
Each technology, available as a Location Provider, offers different capabilities including
differences in power consumption, accuracy, and the ability to determine altitude, speed, or
heading information. Finding Location Providers. The LocationManager class includes static
string constants that return the provider name for three Location Providers:

✓ LocationManager.GPS_PROVIDER
✓ LocationManager.NETWORK_PROVIDER
✓ LocationManager.PASSIVE_PROVIDER

The GPS and passive provider requires fine permission, Network (Cell ID/Wi-Fi) provider
requires fine and coarse. To get a list of the names of all the providers available (based on
hardware available on the device,and the permissions granted the application), call getProviders,
using a Boolean to indicate if you want all, or only the enabled, providers to be returned:

Finding Location Providers by Specifying Criteria. Use the Criteria class to dictate the
requirements of a provider in terms of accuracy, power use(low, medium, high), and the ability
to return values for altitude, speed.

Best Practice for Location Updates

When using Location within your application, consider the following factors:

Battery life versus accuracy - The more accurate the Location Provider, the greater its drain on
the battery.

Startup time - In a mobile environment the time taken to get an initial location can have a
dramatic effect on the user experience — particularly if your app requires a location to be used.
GPS, for example, can have a significant startup time, which you may need to mitigate.

Update rate - The more frequent the update rate, the more dramatic the effect on battery life.
Slower updates can reduce battery drain at the price of less timely updates.

63 | P a g e

You might also like