mobile application development using n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Mobile Application Development using PowerPoint Presentation
Download Presentation
Mobile Application Development using

Loading in 2 Seconds...

play fullscreen
1 / 126

Mobile Application Development using - PowerPoint PPT Presentation


  • 114 Views
  • Uploaded on

Mobile Application Development using . By: Neeraj Sharma. Basics. Introduction. Android is a software stack for mobile devices that includes an operating system, middleware and key applications.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Mobile Application Development using' - berit


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
introduction
Introduction
  • Android is a software stack for mobile devices that includes an operating system, middleware and key applications.
  • Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
  • Android is the first complete, open, and free mobile platform.
introduction cont
Introductioncont.…
  • Android, Inc. was founded in Palo Alto, California, United States in October, 2003 by
  • Andy Rubin (co-founder of Danger),
  • Rich Miner (co-founder of Wildfire Communications, Inc.),
  • Nick Sears (once VP at T-Mobile),
  • Chris White
introduction cont1
Introductioncont.…
  • Google acquired Android Inc. in August, 2005,
  • Making Android Inc. a wholly owned subsidiary of Google Inc.
  • Key employees of Android Inc., including Andy Rubin, Rich Miner and Chris White, stayed at the company after the acquisition.
  • Till May-11 Google has acquired 96 more companies
open handset alliance
Open Handset Alliance
  • Open Handset Alliance (OHA) is a business alliance of 80 firms to develop open standards for mobile devices.
  • Member firms include Google, HTC, Sony, Dell, Intel, Motorola, Qualcomm, Texas Instruments, Samsung, LG, T-Mobil, Nvidia, and Wind River.
  • Goal of the Open Handset Alliance is to develop open standards for mobile devices
android features
Android Features
  • Handset layouts
    • The platform is adaptable to larger, VGA, 2D graphics library, 3D graphics library based on OpenGL ES 2.0 specifications, and traditional smartphone layouts.
  • Storage
    • SQLite, a lightweight relational database, is used for data storage purposes
android features1
Android Features
  • Connectivity
    • Android supports connectivity technologies including GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi (no connections through Proxy server and no Ad hoc wireless network), LTE, NFC and WiMAX.
  • Messaging
    • SMS and MMS are available forms of messaging, including threaded text messaging.
android features2
Android Features
  • Multiple Language Support
    • Multiple Languages are available on Android.
  • Web browser
    • The web browser available in Android is based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine.
  • Media support
    • WebM, 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, OggVorbis, WAV, JPEG, PNG, GIF, BMP.
android features3
Android Features
  • Streaming media support
    • RTP/RTSP streaming (3GPP PSS, ISMA), HTML progressive download (HTML5 <video> tag).
    • Adobe Flash Streaming (RTMP) and HTTP Dynamic Streaming are supported by the Flash 10.1 plugin.
    • Apple HTTP Live Streaming is supported by RealPlayer for Mobile and planned to be supported by the operating system in Android 3.0 (Honeycomb).
    • Microsoft Smooth Streaming is planned to be supported through the awaited port of Silverlight plugin to Android.
software development
Software development
  • Android SDK includes a comprehensive set of development tools.
  • The SDK is downloadable on the android developer website.
  • The officially supported integrated development environment (IDE) is Eclipse (currently 3.5 or 3.6) using the Android Development Tools (ADT) Plugin.
android market
Android Market
  • Android Market is the online software store developed by Google for Android devices.
  • Google announced the Android Market on 28 August 2008, and it was available to users on 22 October 2008.
  • Support for paid applications was available from 13 February 2009 for US and UK developers, with additional support from 29 countries on 30 September 2010.
android market1
Android Market
  • In February 2011, the Android Market was made fully accessible on the web, allowing users to browse and pick up applications using their PCs, send them to their mobile phone and make comments on them. All this functionality was previously accessible only from mobile phone devices.
  • Users can install apps directly using APK files, or from alternative app markets. Unlike Apple, Google allows independent app stores to operate for Android.
downloading and installation of android sdk
Downloading and installation of Android SDK
  • Go to: http://developer.android.com/sdk/index.html
downloading and installation of android sdk1
Downloading and installation of Android SDK

Copy the downloaded zip file to c:\program files and unzip it.

downloading and installation of android sdk2
Downloading and installation of Android SDK

The downloaded SDK contains only basic tools that are not sufficient to develop any application therefore you must update the SDK using SDK Manager.

downloading and installation of android sdk3
Downloading and installation of Android SDK

Installing Available packages.

installing the adt plugin for eclipse
Installing the ADT Plugin for Eclipse
  • Download ADT plugin from

http://developer.android.com/sdk/eclipse-adt.html

installing the adt plugin for eclipse1
Installing the ADT Plugin for Eclipse
  • Go to My Eclipse Menu and click MyEclipse Configuration Center
linux kernel
Linux Kernel
  • Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model.
  • The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.
android runtime
Android Runtime
  • Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.
  • Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently.
android runtime1
Android Runtime
  • The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint.
  • The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.
  • The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.
libraries
Libraries
  • Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework.
application framework
Application Framework
  • A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser.
  • Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data.
  • A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files.
  • A Notification Manager that enables all applications to display custom alerts in the status bar.
  • An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack.
applications
Applications
  • Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others.
  • All applications are written using the Java programming language.
dalvik virtual machine vs java virtual machine
Dalvik Virtual Machine VS Java Virtual Machine
  • JavaVM’s one can find on almost any desktop computer nowadays are Stack-based Virtual Machines (VM).
  • The DalvikVM on the other hand is register based, because on mobile-processors are optimized for register-based execution.
  • Also of register-based VMs allow faster execution times at the expense of programs which are larger after compilation.
application architecture
Application Architecture
  • The Android operating system is a multi-user Linux system in which each application is a different user.
  • By default, the system assigns each application a unique Linux user ID (the ID is used only by the system and is unknown to the application).
  • Each process has its own virtual machine (VM), so an application's code runs in isolation from other applications.
application architecture1
Application Architecture
  • By default, every application runs in its own Linux process.
  • Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications.
application components
Application Components
  • Application components are the essential building blocks of an Android application.
  • There are four different types of application components.
  • Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed.
activities
Activities
  • An activity represents a single screen with a user interface.
  • An activity is implemented as a subclass of Activity.
services
Services
  • A service is a component that runs in the background to perform long-running operations or to perform work for remote processes.
  • A service does not provide a user interface.
  • For example, a service might play music in the background while the user is in a different application.
  • A service is implemented as a subclass of Service.
content providers
Content providers
  • A content provider manages a shared set of application data.
  • You can store the data in the file system, a SQLite database, on the web, or any other persistent storage location your application can access.
  • Through the content provider, other applications can query or even modify the data (if the content provider allows it).
content providers1
Content providers
  • Content providers are also useful for reading and writing data that is private to your application and not shared.
  • A content provider is implemented as a subclass of ContentProvider and must implement a standard set of APIs that enable other applications to perform transactions.
broadcast receivers
Broadcast receivers
  • A broadcast receiver is a component that responds to system-wide broadcast announcements.
  • Many broadcasts originate from the system

for example,

a broadcast announcing that the screen has turned off,

the battery is low, or

a picture was captured.

broadcast receivers1
Broadcast receivers
  • A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object.
managing projects
Managing Projects
  • There are three types of projects, and they all share the same general structure but differ in function:
    • Android Project
    • Test Project
    • Library Project
test project
Test Project
  • These projects contain code to test your application projects and are built into applications that run on a device.
library project
Library Project
  • These projects contain shareable Android source code and resources that you can reference in Android projects.
  • This is useful when you have common code that you want to reuse.
  • Library projects cannot be installed onto a device; however, they are pulled into the .apk file at build time.
set project as library
Set Project as Library
  • In the Package Explorer, right-click the library project and select Properties.
  • In the Properties window, select the "Android" properties group at left and locate the Library properties at right.
  • Select the "is Library" checkbox and click Apply.
  • Click OK to close the Properties window.
referencing a library project
Referencing a Library Project

To add a reference to a library project, follow these steps:

  • In the Package Explorer, right-click the dependent project and select Properties.
  • In the Properties window, select the "Android" properties group at left and locate the Library properties at right.
  • Click Add to open the Project Selection dialog.
  • From the list of available library projects, select a project and click OK.
  • When the dialog closes, click Apply in the Properties window.
  • Click OK to close the Properties window.
building and running
Building and Running
  • During the build process, your Android projects are compiled and packaged into an .apk file, the container for your application binary.
  • It contains all of the information necessary to run your application on a device or emulator.
  • such as compiled .dex files (Dalvikbyte code), a binary version of the AndroidManifest.xml file, compiled resources (resources.arsc) and uncompiled resource files for your application.
building and running1
Building and Running
  • In Eclipse, the ADT plugin incrementally builds your project as you make changes to the source code.
  • Eclipse outputs an .apk file automatically to the bin folder of the project, so you do not have to do anything extra to generate the .apk.
building and running2
Building and Running

Android Debug Bridge (ADB)

All Android applications must be digitally signed before the system will install them on an emulator or device.

There are two ways to do this:

with a debug key (for immediate testing on an emulator or development device)

with a private key (for application distribution).

creating a sample application
Creating a Sample Application

Open Eclipse go to

New->Android Project

the androidmanifest xml file
The AndroidManifest.xml File
  • Every application must have an AndroidManifest.xml file.
  • The manifest presents essential information about the application to the Android system.
  • Information the system must have before it can run any of the application's code.
  • Among other things, the manifest does the following:
the androidmanifest xml file1
The AndroidManifest.xml File
  • It names the Java package for the application. The package name serves as a unique identifier for the application.
  • It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of.
  • It determines which processes will host application components.
the androidmanifest xml file2
The AndroidManifest.xml File
  • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
  • It also declares the permissions that others are required to have in order to interact with the application's components.
  • It declares the minimum level of the Android API that the application requires.
the androidmanifest xml file3
The AndroidManifest.xml File
  • It lists the Instrumentation classes that provide profiling and other information as the application is running.
    • These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.
  • it lists the libraries that the application must be linked against.
avd android virtual device
AVD (Android Virtual Device)
  • An Android Virtual Device (AVD) is an emulator configuration that lets you model an actual device by defining hardware and software options to be emulated by the Android Emulator.
  • From the Eclipse Toolbar click the Android SDK and AVD Manager Button.
  • This will open a window, from the list select “Virtual Devices”, and click New Button.
slide63
View
  • The package android.view provides classes and interfaces related to drawing on the screen.
  • android.view.Viewis a high level abstraction of all views.
  • Package android.widget provides diff. controls.
layouts
Layouts
  • A layout control is still a View object.
  • It doesn’t actually draw anything specific on the screen.
  • It is a parent container for organizing other controls (children).
  • It determine how and where on the screen child controls are drawn.
types of layout
Types of Layout
  • Linear Layout
  • Table Layout
  • Relative Layout
  • Absolute Layout
  • Frame Layout
linearlayout
LinearLayout

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical">

<TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello, I am a TextView"/>

<Buttonandroid:id="@+id/button"android:layout_width="wrap_content" android:layout_height="wrap_content"android:text="Hello, I am a Button"/>

</LinearLayout>

linear layout
Linear Layout
  • This design has 3 Linear layouts.
  • First is the Main Container layout with vertical orientation.
  • Then it contains 2 Linear Layouts with Vertical orientation.
  • The second layout has 4 children.
  • The third layout also has 4 children's.
linear layout1
Linear Layout

Main Container Layout

With vertical orientation

Second Layout with Horizontal Orientation

Row one

Row two

Row Three

Row Four

  • Third Layout with Vertical Orientation
linear layout2
Linear Layout

<LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical">

<LinearLayoutandroid:orientation="horizontal">

<!--Put your child views here-->

</LinearLayout>

<LinearLayoutandroid:orientation="vertical">

<!--Put your child views here-->

</LinearLayout>

</LinearLayout>

load the xml resource
Load the XML Resource

publicvoidonCreate(BundlesavedInstanceState)

{super.onCreate(savedInstanceState);setContentView(R.layout.main_layout);}

Name of your layout file stored in res/layout folder

Change this name to change layout of your activity

table layout
Table Layout
  • TableLayout is a ViewGroup that displays child View elements in rows and columns.
table layout1
Table Layout

<TableLayout>

<TableRow>

<!--Put your child views here-->

</TableRow>

<TableRow>

<!--Put your child views here-->

</TableRow>

</TableLayout>

relative layout
Relative Layout

<RelativeLayout>

<TextViewandroid:id="@+id/label"android:text="Text"/>

<EditTextandroid:id="@+id/entry"android:layout_below="@id/label"/>

<Button android:id="@+id/ok"

android:layout_below="@id/entry"android:text="OK"android:layout_alignParentRight="true"/>

</RelativeLayout>

spinner
Spinner
  • Spinner is a widget similar to a drop-down list for selecting items

Spinner Control

Title or Prompt text

List of items also known as Adapter View

A Single Row

creating array
Creating Array

<stringname="country_prompt">Choose a country</string>

<string-arrayname="country_array"><item>India</item>

<item>USA</item>

<item>China</item><item>Japan</item>

<item>Korea</item></string-array>

Edit strings.xml file to add string and string array

add spinner to layout
Add Spinner to layout

<Spinnerandroid:id="@+id/spinner"android:layout_width="fill_parent"android:layout_height="wrap_content"android:prompt="@string/country_prompt"

android:entries="@array/country_array"

/>

get spinner into java
Get Spinner into Java

Spinner s = (Spinner) findViewById(R.id.spinner);

s.setOnItemSelectedListener(this);

implements OnItemSelectedListener

publicvoidonItemSelected(AdapterView<?> parent, View v, intposition,longrowId) {}

publicvoidonNothingSelected(AdapterView<?> arg0) {}

checkbox
CheckBox

<CheckBoxandroid:id="@+id/checkbox"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="check it out"/>

publicvoidonCheckedChanged(CompoundButton View, booleanisChecked)

{

if(isChecked)

Toast.makeText(this, "Selected",Toast.LENGTH_SHORT).show();

else

Toast.makeText(this, "Not selected",Toast.LENGTH_SHORT).show();

}

creating an alertdialog
Creating an AlertDialog
  • An AlertDialog is an extension of the Dialog class.
  • It is used for dialogs that use any of the following features:
    • A title
    • A text message
    • One, two, or three buttons
    • A list of selectable items (with optional checkboxes or radio buttons)
creating an alertdialog1
Creating an AlertDialog

AlertDialog.Builder builder =newAlertDialog.Builder(this);builder.setMessage("Are you sure you want to exit?").setCancelable(false).setPositiveButton("Yes",new DialogInterface.OnClickListener()

{publicvoidonClick(DialogInterface dialog,int id){}}).setNegativeButton("No",newDialogInterface.OnClickListener(){publicvoidonClick(DialogInterface dialog,int id)

{dialog.cancel();}}).create().show();

adding a list
Adding a list

finalString[] items ={"Red","Green","Blue"};

builder.setItems(items,newDialogInterface.OnClickListener()

{publicvoidonClick(DialogInterface dialog,int item)

{Toast.makeText(getApplicationContext(), items[item],Toast.LENGTH_SHORT).show();}

});

adding checkboxes and radio buttons
Adding checkboxes and radio buttons

builder.setSingleChoiceItems(items,-1,

newDialogInterface.OnClickListener()

{publicvoidonClick(DialogInterface dialog,int item)

{Toast.makeText(getApplicationContext(),items[item],Toast.LENGTH_SHORT).show();}

});

creating a progressdialog
Creating a ProgressDialog

ProgressDialog dialog =ProgressDialog.show(this,"","Loading...",true);

ProgressDialogprogressDialog;progressDialog=newProgressDialog(MyActivity.this);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("Loading...");progressDialog.setCancelable(false);

progressDialog.show();

intents
Intents
  • Activities, services, and broadcast receivers — are

activated through messages, called intents.

  • Intent messaging is a facility for late run-time binding between components in the same or different applications.
  • Intent object, is a data structure holding a description of an operation to be performed.
intent resolution
Intent Resolution
  • Implicit intents
    • Implicit intents are often used to activate components in other applications.
  • Explicit intents
    • Designate the target component by its name
intent
Intent
  • Action
    • A string naming the action to be performed.
  • Data and Type
    • The URI of the data to be acted on and the MIME type of that data.
  • Category
    • A string containing additional information about the kind of component that should handle the intent.
making a call from an activity
Making a call from an Activity.

Intent intent = new Intent(Intent.ACTION_CALL);

intent.setData(Uri.parse("tel:123455"));

startActivity(intent);

<uses-permissionandroid:name="android.permission.CALL_PHONE"/>

calling default web browser
Calling Default Web Browser

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setData(Uri.parse("http://www.google.com"));

startActivity(intent);

<uses-permissionandroid:name="android.permission.INTERNET"/>

open maps
Open Maps

Uri uri = Uri.parse("geo:38.899533,-77.036476");

Intent it = new Intent(Intent.ACTION_VIEW,uri);

startActivity(it);

<uses-permissionandroid:name="android.permission.INTERNET"/>

<uses-permission

android:name="android.permission.ACCESS_FINE_LOCATION"/>

open contacts
Open Contacts

Intent intent = newIntent

(Intent.ACTION_VIEW,Uri.parse("content://contacts/people"));

startActivity(intent);

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

intent filter
Intent Filter
  • The Android system will determine suitable applications for an implicit intent and if several applications exist offer the user the choice to open one.
  • The determination is based on intent filters.
  • To react to a certain implicit intent an application component must register itself via an IntentFilter in the "AndroidManifest.xml" to this event.
  • Otherwise it can only be called by explicit intents.
intent filter example
Intent Filter example

<intent-filter >

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

<data android:mimeType="image/*"/>

<category android:name="android.intent.category.DEFAULT"/>

</intent-filter>

code to handle intent
Code to Handle intent

ImageViewiv=(ImageView)findViewById(R.id.imageView1);

if( getIntent().getExtras()!=null)

iv.setImageURI((Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM));

explicit intent
Explicit Intent

Intent intent = new Intent(this,SecondActivity.class);

intent.putExtra("name", "Neeraj Sharma");

startActivity(intent);

/*Getting extras in second activity*/

Bundle bundle = this.getIntent().getExtras();

String str = bundle.getString("name");

System.out.println("Name ::"+str);

calling activity for result
Calling activity for result

Intent intent = new Intent(this,SecondActivity.class);

intent.putExtra("name", "Neeraj");

startActivityForResult(intent,1);

protectedvoidonActivityResult(intrequestCode, intresultCode, Intent data) {

switch(requestCode){

case 1:

if(resultCode == RESULT_OK){

if(data != null) {

Bundle bundle = data.getExtras();

String str = bundle.getString("Surname");

System.out.println("Surname :"+str);

}}

break;

}

super.onActivityResult(requestCode, resultCode, data);

}

code for second activity
Code for Second Activity

publicbooleanonKeyDown(intkeyCode, KeyEvent event)

{

if(keyCode == KeyEvent.KEYCODE_BACK)

{

Intent data = new Intent();

data.putExtra("surname", "Sharma");

setResult(RESULT_OK, data);

this.finish();

returntrue;

}

returnfalse;

}

introduction1
Introduction
  • One of Google’s most popular services-after searches is Google Maps.
  • Android integrates Google Maps.
  • There is a mapping activity available to users straight off the main Android launcher.
  • More relevant to you, as a developer, are MapView and MapActivity.
  • Which allow you to integrate maps into your own applications.
working with location based services
Working with Location-Based Services
  • The location-based services facility in Android sits on two pillars
    • The mapping API (com.google.android.maps)

provide facilities for you to display a map and manipulate it.

    • And the Location API (android.location)

It handles GPS data and real-time location data.

  • These APIs reach across the Internet to invoke services from Google servers. Therefore Internet connectivity is compulsory for these to work.
obtaining a map api key from google
Obtaining a map-api Key from Google
  • The two keys
    • 1. for emulator 2. For the device

Because the certificate used to obtain the map-api key will differ between development and production.

  • The ADT plug-in uses the debug certificate during development.
  • For production deployment, you’ll likely use a self-signed certificate to sign your .apk file.
  • To obtain a map-api key, you need the certificate that you’ll use to sign your application.
obtaining a map api key from google1
Obtaining a map-api Key from Google
  • First you must locate your debug certificate, which is generated and maintained by Eclipse.
obtaining a map api key from google2
Obtaining a map-api Key from Google
  • keytool -list -alias androiddebugkey -keystore "FULL PATH OF YOUR debug.keystore FILE" -storepass android -keypass android
obtaining a map api key from google3
Obtaining a map-api Key from Google

http://code.google.com/android/maps-api-signup.html

obtaining a map api key from google4
Obtaining a map-api Key from Google

http://code.google.com/android/maps-api-signup.html

permissions library to use maps
Permissions & Library to use Maps

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

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

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

<uses-library android:name="com.google.android.maps"/>

mapview
MapView

<com.google.android.maps.MapView

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:apiKey="Your map API Key Goes Here"

android:id="@+id/mapview"

android:clickable="true"

/>

using overlays
Using Overlays
  • Google Maps provides a facility that allows you to place custom data on top of the map
using overlays1
Using Overlays
  • Maps provides this facility is by allowing you to add a layer on top of the map.
  • Android provides several classes that help you to add layers to a map.
  • The key class for this type of functionality is Overlay, but you can use an extension of this class called ItemizedOverlay.
  • Apart from ItemizedOverlay we have to use number of other classes so first we take a brief overview of each class that we will use.
using overlays2
Using Overlays
  • Drawable
    • setBounds(rect), getIntrinsicHeight() and getIntrinsicWidth()
  • GeoPoint
    • An immutable class representing a pair of latitude and longitude, stored as integer numbers of micro degrees (degrees * 1E6).
latitude and longitude
Latitude and Longitude
  • Any location on Earth is described by two numbers--its latitude and its longitude.
itemizedoverlay
ItemizedOverlay
  • A sub class for an Overlay which consists of a list of OverlayItems.
  • This handles sorting north-to-south for drawing, creating span bounds, drawing a marker for each point, and maintaining a focused item.
  • It also matches screen-taps to items, and dispatches Focus-change events to an optional listener.
itemizedoverlay1
ItemizedOverlay

Drawablemarker = getResources().getDrawable(R.drawable.map_marker);

marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());

geopoint
GeoPoint

GeoPointdisneyMagicKingdom = newGeoPoint((int) (28.418971 * 1E6), (int) (-81.581436 * 1E6));

GeoPointdisneySevenLagoon = newGeoPoint((int) (28.410067 * 1E6), (int) (-81.583699 * 1E6));

overlayitems
OverlayItems

classInterestingLocationsextendsItemizedOverlay

{

private List<OverlayItem> locations = newArrayList<OverlayItem>();

privateDrawablemarker;

publicInterestingLocations(Drawable marker) {

super(marker);

this.marker = marker;

GeoPointdisneyMagicKingdom = newGeoPoint((int) (28.418971 * 1E6), (int) (-81.581436 * 1E6));

GeoPointdisneySevenLagoon = newGeoPoint((int) (28.410067 * 1E6), (int) (-81.583699 * 1000000));

locations.add(newOverlayItem(disneyMagicKingdom, "Magic Kingdom","Magic Kingdom"));

locations.add(newOverlayItem(disneySevenLagoon, "Seven Lagoon","Seven Lagoon"));

populate();

}

publicvoid draw(Canvas canvas, MapViewmapView, boolean shadow) {

super.draw(canvas, mapView, shadow);

boundCenterBottom(marker);

}

protectedOverlayItemcreateItem(int i) {

returnlocations.get(i);

}

publicint size() {

returnlocations.size();

}}

overlayitems1
OverlayItems

mapView = (MapView) findViewById(R.id.mapview);

mapView.setBuiltInZoomControls(true);

mapView.setClickable(true);

Drawablemarker = getResources().getDrawable(R.drawable.map_marker);

marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());

InterestingLocationsfunPlaces = newInterestingLocations(marker);

mapView.getOverlays().add(funPlaces);

GeoPointpt = funPlaces.getCenter(); // get the first-ranked point

mapView.getController().setCenter(pt);

mapView.getController().setZoom(15);

geocoding with android
Geocoding with Android
  • Converting an address (or location) to a latitude / longitude pair is known as geocoding.
  • android.location.Geocoder class provides this facility.
  • Geocoder class provides both forward and backward conversion.
    • Address to co-ordinates
    • Co-ordinates to list of address
geocoder
GeoCoder

List<Address> getFromLocation(double latitude, double longitude, intmaxResults)

List<Address> getFromLocationName(String locationName, intmaxResults, double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude)

List<Address> getFromLocationName(String locationName, intmaxResults)

layout
Layout

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<LinearLayoutandroid:layout_width="fill_parent"android:layout_alignParentBottom="true"

android:orientation="vertical"android:layout_height="wrap_content">

<EditTextandroid:layout_width="fill_parent"android:layout_height="wrap_content"

android:text="White House"android:id="@+id/location"/>

<Buttonandroid:id="@+id/geocodeBtn"android:layout_width="wrap_content"

android:text="Find Location" android:layout_height="wrap_content"/></LinearLayout>

<com.google.android.maps.MapViewandroid:id="@+id/geoMap"

android:clickable="true"

android:layout_width="fill_parent"

android:layout_height="320px"

android:apiKey="YOUR API KEY GOES HERE"/>

</RelativeLayout>

layout1
Layout

publicclassGeocodingDemoActivityextendsMapActivity{

Geocodergeocoder = null;

MapViewmapView = null;

protectedbooleanisLocationDisplayed() { returnfalse; }

protectedbooleanisRouteDisplayed() { returnfalse; }

protectedvoidonCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

mapView = (MapView)findViewById(R.id.geoMap);

mapView.setBuiltInZoomControls(true);

// lat/long of Jacksonville, FL

intlat = (int)(30.334954*1E6);

intlng = (int)(-81.5625*1E6);

GeoPointpt = newGeoPoint(lat,lng);

mapView.getController().setZoom(10);

mapView.getController().setCenter(pt);

layout2
Layout

Button geoBtn =(Button)findViewById(R.id.geocodeBtn);

geocoder = newGeocoder(this);

geoBtn.setOnClickListener(newOnClickListener(){

publicvoidonClick(View arg0) {

try {

EditTextloc = (EditText)findViewById(R.id.location);

String locationName = loc.getText().toString();

List<Address> addressList = geocoder.getFromLocationName(locationName, 5);

if(addressList!=null && addressList.size()>0){

intlat = (int)(addressList.get(0).getLatitude()*1E6);

intlng = (int)(addressList.get(0).getLongitude()*1E6);

GeoPointpt = newGeoPoint(lat,lng);

mapView.getController().setZoom(15);

mapView.getController().setCenter(pt);

}

} catch (IOException e) { e.printStackTrace(); }

}});

}}

locationmanager and locationprovider
LocationManager and LocationProvider
  • A LocationProvider provides location data using several metrics, and you can access providers through a LocationManager.
  • LocationManagerallows you to attach a LocationListener that receives updates when the device location changes.
  • This service provides two things: a mechanism for you to obtain the device’s geographical location, and a facility for you to be notified (via an intent) when the device enters a specified geographical location.
locationmanager and locationprovider1
LocationManager and LocationProvider

LocationManagerlocMgr=(LocationManager)getSystemService (Context.LOCATION_SERVICE);

Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);

List<String> providerList = locMgr.getAllProviders();

for( String s: providerList)

Log.v("Location Manager ",s);

listening location updates
Listening location updates

LocationManagerlocMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

LocationListenerlocListener = newLocationListener() {

publicvoidonLocationChanged(Location location) {

if (location != null)

Toast.makeText(getBaseContext(),"New location latitude [" + location.getLatitude()+ "] longitude [" + location.getLongitude()+ "]", Toast.LENGTH_SHORT).show();

}

publicvoidonProviderDisabled(String provider) {}

publicvoidonProviderEnabled(String provider) {}

publicvoidonStatusChanged(String provider, int status, Bundle extras) { }

};

locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,

0, // minTime in ms

0, // minDistance in meters

locListener);

assignment
Assignment
  • Explore and Learn about MyLocationOverlay class and explain with a running example