79
Getting started with Gunjan Kumar

Getting started with android dev and test perspective

Embed Size (px)

DESCRIPTION

The presentation covers basic intro to Android, how to get started with development, including instructions on setup, common UI usages like menus, dialogs; details on services like Sensors, Location and Google Maps It also covers ideas on how to test including details on shell and installation instructions without using Eclipse

Citation preview

Page 1: Getting started with android   dev and test perspective

Getting started with

Gunjan Kumar

Page 2: Getting started with android   dev and test perspective

Agenda

Overview of Android Features and Architecture

Setup for development (SDK, ADT) Android Virtual Device

Installing, using and installing applications Developing Android applications Install / test on AVD Ideas for testing

Page 3: Getting started with android   dev and test perspective

OVERVIEW OF ANDROID

Page 4: Getting started with android   dev and test perspective

Overview Android is a software stack for mobile devices that includes an

operating system, middleware and key applications Based on the Linux kernel Open Handset Alliance collaborated on Android's development

and release More than 33% of market share today. 3.1 Honeycomb for Tablet and 2.3.4 Gingerbread for Phones App market with 200000+ apps, >3 billion downloads

http://en.wikipedia.org/wiki/Android_%28operating_system%29

Page 5: Getting started with android   dev and test perspective

History Android Inc founded in 2003 by Andy Rubin and other

members. Google acquired Android in August 2005. Open Handset Alliance formed on 5 November 2007 to

develop open standards for mobile devices. Android unveiled as OHA’s first product. Updates launched to fix bugs / add new features The code names are in alphabetical order (Cupcake, Donut,

Eclair, Froyo, Gingerbread, Honeycomb, and the upcoming Ice Cream Sandwich).

Page 6: Getting started with android   dev and test perspective

Version historyVersion

Name Release Date

Beta 5 November 2007

1.0 23 September 2008 Android Market, Google account integration, maps …

1.1 9 February 2009 resolved issues, API changes …

1.5 Cupcake 30 April 2009 Widgets, upload to YouTube and Picasa …

1.6 Donut 15 September 2009 WVGA / CDMA support, Google navigation, Search enhancement …

2.0/2.1 Éclair 26 October 2009 / 12 January 2010

Live wallpaper, multiple screen resolutions, Camera flash …

2.2 Froyo 20 May 2010 Chrome’s V8 JavaScript engine, upload file in browser …

2.3 Gingerbread 6 December 2010 Voice and Video support in Gtalk …

3.0 / 3.1

Honeycomb 22 February 2011 / 10 May 2011

Released for tablets

Ice Cream Sandwich

Q4 2011 combination of Gingerbread and Honeycomb into a "cohesive whole"http://en.wikipedia.org/wiki/Android_version_history

Page 7: Getting started with android   dev and test perspective

Usage share / Market Share

Source Year Symbian Android RIM iOS Microsoft Other OSs

Gartner 2011 Q1 27.4% 36.0% 12.9% 16.8% 3.6% 3.3%

Gartner 2010 37.6% 22.7% 16.0% 15.7% 4.2% 3.8%

Gartner 2009 46.9% 3.9% 19.9% 14.4% 8.7% 6.1%

Gartner 2008 52.4% 0.5% 16.6% 8.2% 11.8% 10.5%

Gartner 2007 63.5% N/A 9.6% 2.7% 12.0% 12.1%

Page 8: Getting started with android   dev and test perspective

Features Application framework enabling reuse and replacement of components Dalvik virtual machine optimized for mobile devices Integrated browser based on the open source WebKit engine Optimized graphics powered by a custom 2D graphics library; 3D

graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)

SQLite for structured data storage Media support for common audio, video, and still image formats

(MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent) Rich development environment including a device emulator, tools for

debugging, memory and performance profiling, and a plugin for the Eclipse IDE

http://developer.android.com/guide/basics/what-is-android.html

Page 9: Getting started with android   dev and test perspective

http://developer.android.com/images/system-architecture.jpg

Android architecture

Page 10: Getting started with android   dev and test perspective

SETUP FOR DEVELOPMENT

Page 11: Getting started with android   dev and test perspective

App development overview An open development platform, Android offers developers the

ability to build extremely rich and innovative applications Underlying all applications is a set of services and systems,

including: A rich and extensible set of Views that can be used to build an

application, including lists, grids, text boxes, buttons, and even an embeddable web browser

Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data

A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files

A Notification Manager that enables all applications to display custom alerts in the status bar

An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack

Page 12: Getting started with android   dev and test perspective

App development : options http://appinventor.googlelabs.com/about/ SDK provided so you can use command line or IDE for app

development Eclipse based development for more elaborate development

SDK + ADT (Android Developer Tool) Set up Android Virtual Devices or hardware devices. Create an Android project. Build and run your application. Debug your application with the SDK debugging and logging tools. Test your application with the Testing and Instrumentation

framework.

Page 13: Getting started with android   dev and test perspective

Step 1 : Install SDK System requirement :

http://developer.android.com/sdk/requirements.html

So ensure you have JDK installed before you move to SDK installation

Download from http://developer.android.com/sdk/index.html

Launch SDK Manager from the downloaded file to install platforms

http://developer.android.com/sdk/installing.html

Page 14: Getting started with android   dev and test perspective

Step 1 : Install SDK- tips Ensure that JDK is installed.

http://java.sun.com/javase/downloads/index.jsp

Once JDK is installed, you can either use Installer or download ZIP for Android SDK

http://developer.android.com/sdk/index.html Once SDK is installed, you will see a SDK

Manager executable in the folder. Launch this to download platforms that will

get added to the platforms folder In office, you may have issues downloading

from https so in the SDK manager, goto settings and check on the “force HTTPS to be fetched as HTTP” checkbox

If that doesn’t work out as well, try setting a proxy (say proxy-ne7.qintra.com port 8888 )

Alternatively, you can copy this folder from any existing installation

Page 15: Getting started with android   dev and test perspective

Step 2 : Eclipse plug-in – Why?

ADT (Android Developer Tool) plug-in for Eclipse simplifies development in Eclipse by providing

Android Project Wizard helps create new project

Forms-based manifest, layout and resource editor Building, conversion to .DEX (Android Executable), package to .APK and install

to Dalvik VM is automated AVD manager integrated with Eclipse for easy access to AVDs DDMS (Dalvik Debug Monitoring Services) assists in monitoring Debugging, breakpoints Log and console outputs

Page 16: Getting started with android   dev and test perspective

Step 2 : Eclipse plug-in : How?

•Help Install new software•Add the following URL

•http://dl.google.com/android/eclipse•Select all from the Developer Tools•Restart and update ADT Preference

•Window Preference•Mention the SDK Location

Page 17: Getting started with android   dev and test perspective

ANDROID VIRTUAL DEVICE

Page 18: Getting started with android   dev and test perspective

Development in Eclipse

Page 19: Getting started with android   dev and test perspective

Create AVD and launch Emulator (command line) 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.

See list of targets : android list targets id: 2 or "android-4"

     Name: Android 1.6     Type: Platform     API level: 4     Revision: 3     Skins: QVGA, HVGA (default), WVGA800, WVGA854

Create AVD : android create avd -n my_avd -t 2

Run Emulator : emulator -avd <avd_name>

http://developer.android.com/guide/developing/devices/managing-avds-cmdline.htmlhttp://developer.android.com/guide/developing/tools/emulator.html

Page 20: Getting started with android   dev and test perspective

Create AVD from SDK Manager

Page 21: Getting started with android   dev and test perspective

Create AVD from Eclipse

Page 22: Getting started with android   dev and test perspective

Specifying details for AVD

SD Card must be at least 9MB or left blank

Skin allows to choose resolution / form factor for the device you want to emulate

Name the device and select the target (the version of Platform that you want to emulate. Note that the list will be pulled out from the list of platforms you have installed on your machine (you can see in <sdk>\ platforms folder)

Page 23: Getting started with android   dev and test perspective

Emulator

Page 24: Getting started with android   dev and test perspective

DEVELOPING ANDROID APPLICATIONS

Page 25: Getting started with android   dev and test perspective

Activities Presentation layer Activity is a screen – only one gets user inputs at a time An application can have more than one activities, each being a

screen that the app can show to the user Each activity extends android.app.Activity onCreate method is overridden to create or set the view – the

actual layout of controls on the screen

Page 26: Getting started with android   dev and test perspective

Services Run in background, with no visible UI Extend Service class Typically used to develop services that need to be running

even if the screen is closed

Page 27: Getting started with android   dev and test perspective

Intent Message passing mechanism within and between applications Used for

Starting a service or activity Broadcast that an event has occurred – Android broadcasts intents

for system events like “incoming phone call” Declare your intent that an activity be started to perform an action

with some data

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL)); startActivity(browserIntent);

Intent callIntent = new Intent(Intent.ACTION_CALL);callIntent.setData(Uri.parse("tel:" + PhoneNumber));startActivity(callIntent);

void OpenHome(){ Intent myIntent = new Intent(QwestAvailabilityDetails.this, QwestHome.class); startActivity(myIntent); }

Page 28: Getting started with android   dev and test perspective

Content Provider Shareable data sources Native content stores exposed by Android – media store,

contacts, call logs etc.

Page 29: Getting started with android   dev and test perspective

Create new app

Specify the project name as it should appear in your workspace

Specify the target platform – depending on the device you are expecting this to run on

Application Name – as will appear on the deviceCreate Activity – the first activity that will be launched when app starts

Page 30: Getting started with android   dev and test perspective

What is generated?Named as the Create Activity specified when creating the app, this extends android.app.Activity and serves as the “screen” that is shown to the userAuto generated file. DON’T MANIPULATE. Contains reference to all resources. Used in activities to access the resourcesContains resources – layouts, images, values to be used in app – referenced via R

Contains the icon which will be used on device for your app.Any more images that you use in the app must be added here.Add versions based on resolution to each of the folders

Layouts specify the screens look and feel – think of it as HTML.Typically, you will have one layout for each activity.Main.xml is generated by default to correspond to the initial activity created by default

Gives details like package, activity to be launched when app starts, permissions and intents – app configuration file of sorts

Contains values specified as type, name and value. Can be of types other than string (say colors)Gives flexibility of configuring based on environment – one set for each environment

Contains all the source code

Page 31: Getting started with android   dev and test perspective

AndroidManifest.xml Information for android to run your application like

Package name / application name<manifest package="com.qwest.techfriday.android“ android:versionCode="1“ android:versionName="1.0">

List of all components – activities, services etc.<activity android:name=".DemoViews" android:label="@string/app_name">

Identifies the activity which will be launched on app start<activity android:name=".QwestHome" android:label="@string/app_name">

<intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

Permissions to access protected parts of the API and interact with other applications

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

lists the libraries that the application must be linked against<uses-library android:name="com.google.android.maps" />

http://developer.android.com/guide/topics/manifest/manifest-intro.html

Page 32: Getting started with android   dev and test perspective

UI concepts : View View – basic unit of UI expression

Can be specified as XML in res/layout folder and then inflated in the activity

setContentView(R.layout.alert);

Can be dynamically created and added to activity – partly (from another layout) or fully (creating and adding controls)

//We set a view to be shown on the page – this serves as outer shell setContentView(R.layout.materpage); //To this shell, we inflate another view which is present in another XMLTableLayout tlContainer = (TableLayout) findViewById(R.id.containerForIndividualLayout);LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.viewbill, null); tlContainer.addView(itemView, new TableLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

Page 33: Getting started with android   dev and test perspective

UI Concepts : View Dynamically creating views and adding to layout

View mainPanel = CreateView(); setContentView(R.layout.materpage); TableLayout tlContainer = (TableLayout) findViewById(R.id.containerForIndividualLayout); tlContainer.addView(mainPanel);

private ViewGroup CreateView() {LinearLayout panel = new LinearLayout(this);panel.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));panel.setOrientation(LinearLayout.VERTICAL);panel.setPadding(10, 0,0,0);panel.setBackgroundColor(Color.TRANSPARENT); TextView txtHeader = new TextView(getApplicationContext());txtHeader.setText("Congratulations! You qualify for the following products.");txtHeader.setTextSize(20);

Page 34: Getting started with android   dev and test perspective

UI Concepts : Layout Layout – type of layout architectures telling how the children

are aligned LinearLayout : aligns all children in a single direction — vertically

or horizontally RelativeLayout : child views specify their position relative to the

parent view or to each other TableLayout : positions its children into rows and columns FrameLayout : Blank space where children are pinned to top left

corner

http://developer.android.com/guide/topics/ui/layout-objects.html

Page 35: Getting started with android   dev and test perspective

UI Concepts: Widgets and events Inherit from android.widget Serves as an interface for interaction with the user Buttons, text views (editable / read only), date picker etc.

Once View / Widgets defined, you want to know of user interactions – do use events

Define an event listener and register it with the ViewbtnAlert.setOnClickListener(this);

ORalertDialog.setButton("Btn1", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {

showToast(message + ". You pressed Btn1 : " + which, getApplicationContext());

View class gives multiple callback methods by default onClick / onLongClick / onFocusChange / onTouch etc.

http://developer.android.com/guide/topics/ui/ui-events.html

Page 36: Getting started with android   dev and test perspective

UI Concepts: Options Menu This is shown when Menu button of phone is pressed

Create a view under res/menu/ for look and feel Define appearance for the menu (onCreateOptionsMenu)

either from view OR dynamically Respond to user selection (onOptionsItemSelected)

For submenu, add menu as child to item in the view.

http://developer.android.com/guide/topics/ui/menus.html

Page 37: Getting started with android   dev and test perspective

UI Concepts: Options Menu

http://developer.android.com/guide/topics/ui/menus.html

@Overridepublic boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true;}

@Overridepublic boolean onOptionsItemSelected(MenuItem item) {

// Handle item selection switch (item.getItemId()) {

case R.id.menu_item_alerts: //todoreturn true; case R.id.menu_item_views:

//todo return true; default: return super.onOptionsItemSelected(item);

}}

resource main_menu is defined with items like : <item android:id="@+id/menu_item_alerts" android:icon="@drawable/icon_menu_alert" android:title="Alerts Demo" />

Page 38: Getting started with android   dev and test perspective

UI Concepts: Context Menu This is shown when a control is pressed for long Similar to the “right click” on PC Create it for any view

Create a view under res/menu/ for look and feel Register that view for a context menu

(registerForContextMenu) Define appearance for the menu (onCreateContextMenu)

either from view OR dynamically Respond to user selection (onContextItemSelected)

Page 39: Getting started with android   dev and test perspective

UI Concepts: Context Menu

@Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu);}

@Overridepublic boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.ctx_menu_item_option_1: showToast("context menu option 1 selected", getApplicationContext());return true;

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState setContentView(R.layout.alert); txtAlertName = (EditText)findViewById(R.id.txtAlertName); registerForContextMenu(txtAlertName);

Page 40: Getting started with android   dev and test perspective

UI Concepts: Alerts / Dialogs

Toast

AlertDialog

ProgressDialog

DatePickerDialog TimePickerDialog

Page 41: Getting started with android   dev and test perspective

UI Concepts: Alerts / Dialogs

int duration = Toast.LENGTH_SHORT;Toast toast = Toast.makeText(appContext, message, duration);toast.show();

TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {@Overridepublic void onTimeSet(TimePicker view, int hourOfDay, int minute) {

//TODO : When user selects time}};TimePickerDialog timePicker = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, true);timePicker.show();

DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {@Overridepublic void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

//TODO : when user selects Date}};DatePickerDialog datePicker = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);datePicker.show();

Toast

DatePickerDialog

TimePickerDialog

Page 42: Getting started with android   dev and test perspective

UI Concepts: Alerts / Dialogs

ProgressDialog dialog = new ProgressDialog( DemoAlerts.this);dialog.setMessage("This is the content you want to show - like please wait while we fetch your account details...");dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// this gives progress bardialog.show();

AlertDialog alertDialog = new AlertDialog.Builder(this).create();alertDialog.setTitle("This is the title for the window");alertDialog.setMessage("The dialog message goes here. This can be any text and as per the length, it will wrap this.");

alertDialog.setButton("Btn1", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {//TODO on button click }});alertDialog.setButton2("Btn2", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {//TODO on button click }});alertDialog.setButton3("Btn3", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {//TODO on button click }});alertDialog.setIcon(R.drawable.icon);alertDialog.show();

ProgressDialog

AlertDialog

Page 43: Getting started with android   dev and test perspective

UI Concepts: Status Bar Notification Primarily for services to notify the user

Get a reference to the NotificationManager Instantiate the Notification Define the Notification's expanded message and Intent Pass the Notification to the NotificationManager

http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Page 44: Getting started with android   dev and test perspective

SESSION 2 : Agenda Quick recap of last session and any open questions Sensors Location based services Geocoding / reverse geocoding Maps Console Testing ideas

Page 45: Getting started with android   dev and test perspective

Sensors SensorManager lets you access device sensors Like other system services, you need to get a reference to it

getSystemService(SENSOR_SERVICE)

Determine the sensor you want to listen to (accelerometer, orientation, temperature etc.)

private static final int sensorToListenFor = SensorManager.SENSOR_ORIENTATION;

Since services work in a publish-subscribe mode, implement a listener and override the onSensorChanged

One of the values you get is “float[] values” and this will contain values depending on the type of sensor you are listening to

http://developer.android.com/reference/android/hardware/SensorEvent.html#values

Since sensors involve lot of processing to get the data, register and unregister to save battery and processing power

http://developer.android.com/reference/android/hardware/SensorManager.html

Page 46: Getting started with android   dev and test perspective

Sensors Example - orientation Get an instance by calling Context.getSystemService

sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

Determine the sensors you want to get data from private static final int sensorToListenFor =

SensorManager.SENSOR_ORIENTATION;

Implement a listener and override onSensorChanged

Register and unregister listener to this in the resume and pause

http://developer.android.com/reference/android/hardware/SensorManager.html

@Override public void onResume() / onPause() { super.onResume(); sensorManager.registerListener / unregisterListener (this, sensorToListenFor); }

public void onSensorChanged(int sensor, float[] values) {if(sensor == sensorToListenFor){

float azimuth = Math.round(values[0]);float pitch = Math.round(values[1]);float roll = Math.round(values[2]);

Page 47: Getting started with android   dev and test perspective

Sensors Example - orientation

values[0]: Azimuth, angle between the magnetic north direction and the y-axis, around the z-axis (0 to 359). 0=North, 90=East, 180=South, 270=West values[1]: Pitch, rotation around x-axis (-180 to 180), with positive values when the z-axis moves toward the y-axis. values[2]: Roll, rotation around y-axis (-90 to 90), with positive values when the x-axis moves toward the z-axis.

Page 48: Getting started with android   dev and test perspective

Sensors - testing Almost all sensors require a physical device to test Emulator OR console DO NOT offer commands to simulate

sensor values Few open source options like

http://code.google.com/p/openintents/wiki/SensorSimulator which can simulate sensors

Page 49: Getting started with android   dev and test perspective

Sensor testing : snapshots from phone

Azimuth around 0 – phone is pointing in the North direction

Azimuth around 90 – phone is pointing in the East direction

Azimuth around 180 – phone is pointing in the South direction

Azimuth around 270 – phone is pointing in the West direction

Pitch around 0 – phone is “lying flat”Pitch around -90 – phone is “standing” Pitch around 90 – phone is “standing on its head”

Roll around 0 – phone is “lying flat”Roll around -90 – phone is “standing on its side”

Page 50: Getting started with android   dev and test perspective

Location Based Services Location services of the device are accessible through

android.location LocationManager is a system service that provides APIs for access to

device location There are multiple location providers (GPS, Network etc.) and we need

to select the provider to use

Request an instance of LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE)

Get last known location Location lastKnown = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)

Add a hook to listen to location updates (implement LocationListener) lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener)

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

http://developer.android.com/guide/topics/location/obtaining-user-location.html

Page 51: Getting started with android   dev and test perspective

Location Listener and Manager requestLocationUpdates

provider: The name of the provider with which you register minTime: The minimum time interval for notifications, in milliseconds. minDistance: The minimum distance interval for notifications, in meters. listener: An object whose onLocationChanged() method will be called for each

location update.

LocationListener onLocationChanged(Location location): This method is called when the location

has changed. onProviderDisabled(String provider): This method is called when the provider is

disabled by the user. onProviderEnabled(String provider): This method is called when the provider is

enabled by the user. onStatusChanged(String provider, int status, Bundle extras): This method is

called when the provider status changes

Location .getLatitude() and .getLongitude() used to get latitude and longitude

http://www.devx.com/wireless/Article/39239/1954

Page 52: Getting started with android   dev and test perspective

Location : Testing Location can be sent as individual co-ordinate OR KML (refer

to http://code.google.com/apis/kml/documentation/kml_tut.html)

You can also use console are given in next slide To get a KML for a route, you can use a URL like below to get

the path in KML format http://maps.google.co.in/maps?

f=d&hl=en&saddr=12.958528,77.704747&daddr=12.93625,77.690073&ie=UTF8&0&om=0&output=kml

Page 53: Getting started with android   dev and test perspective

Location : Testing : Sending location from console Open console : telnet localhost <emulator number>

telnet localhost 5554

Background : geocoding allows you to get geo location from an address

If you try a URL like : http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Glenarm+place,+Denver,+CO&sensor=true

<geometry><location><lat>39.7442190</lat><lng>-104.9894830</lng></location>

In applications that use device’s current location we can test by sending different locations from console

http://developer.android.com/guide/developing/devices/emulator.html

Page 54: Getting started with android   dev and test perspective

Geocoding Geocoding is the process of relating location and other geographic

data like address, zip code etc Forward geocoding

also referred to as simply Geocoding Process of getting location from geographic data Using Google Map API WS, you can just enter a URL like below to get an XML (you

can also get JSON by using geocode/JSON? instead of geocode/xml? http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Glenarm+place,+Denver,+CO&sensor=true

Reverse geocoding Process of getting geographic data like Address / Postal Code from location Using Google Map API WS, you can use a URL like below to get the address in XML /

JSON format. Note that this can be approximate match PLUS can return more than one address

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true_or_false

http://code.google.com/apis/maps/documentation/geocoding/index.html

Page 55: Getting started with android   dev and test perspective

Geocoding support in Android Geocoder has methods getFromLocation and

getFromLocationName for forward and reverse geocode Geocoder geoCoder = new Geocoder(appContext , Locale.getDefault());

try {List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(), 10);

for(Address currentAddress : addresses) {lblShowLocation.append("\n" + currentAddress.getAddressLine(0));

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

http://developer.android.com/reference/android/location/Geocoder.html

try {List<Address> locations= geocoder.getFromLocationName(“1600 Glenarm Place, Denver, CO”, 10);

for(Address currentLocation: locations) {lblShowLocation.append("\n" + currentLocation .getLatitude());

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

Page 56: Getting started with android   dev and test perspective

Maps Google Maps is an external library Download the api (Requires Android SDK 1.5 or above)

http://code.google.com/android/add-ons/google-apis/installing.html

Register api key http://code.google.com/android/add-ons/google-apis/mapkey.html

MapView is the Map View control MapActivity is the base class you extend in your activity Overlay is used to annotate your maps

You can use a canvas to draw MapController used to center location, zoom etc. ItemizedOverlays and OverlayItems used to create layer of

map markers

http://developer.android.com/guide/tutorials/views/hello-mapview.html

Page 57: Getting started with android   dev and test perspective

Maps : register API key Run the following to get your MD5 cert

keytool -list -alias androiddebugkey -keystore <path_to_debug_keystore>.keystore -storepass android -keypass android

Goto : http://code.google.com/android/maps-api-signup.html Enter the MD5 signature Use the key in MapView

C:\>keytool -list -alias androiddebugkey -keystore "C:\Documents and Settings\gxkumar\.android\debug.keystore" -storepass android -keypass androidandroiddebugkey, Jun 22, 2011, PrivateKeyEntry,Certificate fingerprint (MD5): 32:E4:29:6C:2B:98:9C:33:41:5F:7F:43:CA:04:C7:33

http://code.google.com/android/add-ons/google-apis/mapkey.html

Page 58: Getting started with android   dev and test perspective

Maps : how to show map? Create activity that extends MapActivity

isRouteDisplayed needs to be overridden mandatorily

Add MapView to your layout along with the apiKey<com.google.android.maps.MapView … android:apiKey=

“Maps_ApiKey_String“/>

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

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

When location changes, the map will NOT center to it by default. We need to handle that via MapController.setCenter(GeoPoint point)

http://developer.android.com/guide/tutorials/views/hello-mapview.html

Page 59: Getting started with android   dev and test perspective

Maps : respond to location update

To add zoom controls:mapView = (MapView)findViewById(R.id.mapview);mapView.setBuiltInZoomControls(true);

To show the location on mapIn the onCreate method : MapController mc = mapView.getController();

In listener : public void onLocationChanged(Location loc) {……GeoPoint p = new GeoPoint( (int) (loc.getLatitude() * 1E6), (int) (loc.getLongitude() * 1E6)); mc.animateTo(p); mc.setZoom(13);

To set view of mapmapView.setSatellite(true);mapView.setStreetView(true);

http://mobiforge.com/developing/story/using-google-maps-android

Page 60: Getting started with android   dev and test perspective

Maps : overlays Overlays are layers added one over other on top of map They are inherently transparent Mostly used to add markers / draw on the map

Overlay is providing a canvas to draw on

Two options to ad overlays to map Implement a class that extends Overlay

Override draw method to allow you to draw on the canvas Use projections to translate geo points to canvas points Override onTap to do some action when a geo point is tapped by the user

Implement a class that extends ItemizedOverlay<OverlayItem> Each overlay item is defined by GeoPoint, Text and Snippet Override draw to allow to draw on canvas – say connect locations

Page 61: Getting started with android   dev and test perspective

Maps : add markerAdd Markers//get the overlays and clear itList<Overlay> mapOverlays = mapView.getOverlays();mapOverlays.clear(); //first we need to define the drawable using one of the iconsDrawable drawable = this.getResources().getDrawable(R.drawable.icon_map_marker);//initialize the itemized overlay using the current markerCustomItemizedOverlay mapOverlay = new CustomItemizedOverlay(drawable);

GeoPoint point = new GeoPoint((int) (( loc.getLatitude()) * 1E6), (int) ((loc.getLongitude()) * 1E6));

OverlayItem overlayitem = new OverlayItem(point, "title", "snippet");mapOverlay.addOverlay(overlayitem); mapOverlays.add(mapOverlay); mapView.invalidate();

class CustomItemizedOverlay extends ItemizedOverlay

Page 62: Getting started with android   dev and test perspective

Maps : keep adding markers

public void AddLocationToMap(Location loc) { //get the overlays and clear it List<Overlay> mapOverlays = mapView.getOverlays(); mapOverlays.clear(); GeoPoint point = new GeoPoint((int) (( loc.getLatitude()) * 1E6),

(int) ((loc.getLongitude()) * 1E6)); String addressForPoint = ""; addressForPoint = GetAddressFromPoint(point, getApplicationContext()); lblAddress.setText(addressForPoint); //create an overlay items OverlayItem overlayitem = new OverlayItem(point, "Address : "

+ addressForPoint, "snippet"); //add it to the our customized overlay item list itemizedOverlay.addOverlay(overlayitem); //add the current list to mapOverlays mapOverlays.add(itemizedOverlay); //invalidate will force to redraw the map mapView.invalidate();

}

Page 63: Getting started with android   dev and test perspective

Caution while listening for location change

This is the screen capture from my cell after 500m of walking.

Current setting was “locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1”

Also keep in mind that the location fixed by GPS can keep varying so be sure you are not using less accurate points

Depending on your application’s need, alter the frequency of check and distance change when listener should report a change.

Remember – GPS will consume battery and data so use it wisely

Page 64: Getting started with android   dev and test perspective

Maps : sample app for tracking your path

Few key things to note Since the app used to un-register from Location

Listening onPause, the area where cell phone screen was off – there were no locations captured

So depending on your app, decide whether you want to listen always or not

Frequency of listening is very critical Listen more frequently – and you end up showing lot of points Listen less frequently and your path is not plotted correctly

Page 65: Getting started with android   dev and test perspective

INSTALL / TEST ON AVD

Page 66: Getting started with android   dev and test perspective

Installing and running the app The executable is a .APK file which can be installed on device

or run on emulator

SDK includes a virtual mobile device emulator Create AVD with required configuration and run on emulator

Controls in emulator for most functionality. Each emulator instance provides a control console the you can

connect to, to issue commands that are specific to that instance.

http://developer.android.com/guide/developing/devices/emulator.html

Page 67: Getting started with android   dev and test perspective

Install APK to AVD Ensure that AVD is created and

emulator is running Place .apk file in /tools folder on

SDK On the command prompt, goto

android SDK /tools folder: adb install my_android_app.apk

The apk file can be located anywhere – you just need the path when running this command

Once this is complete, you can see the app installed in your home / app

http://www.android.pk/blog/general/how-to-install-apk-files-on-android-emulator/

Page 68: Getting started with android   dev and test perspective

Console Each running emulator instance includes a console facility that

lets you dynamically query and control the simulated device environment

telnet localhost <console-port>. Console Port starts with 5554

Once console is launched, you can use commands to send events, location change etc to the device

http://developer.android.com/guide/developing/devices/emulator.html

Page 69: Getting started with android   dev and test perspective

Example : Sending geocode from console Background : geocoding allows you to get geo location from

an address If you try a URL like :

http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Glenarm+place,+Denver,+CO&sensor=true

<geometry><location><lat>39.7442190</lat><lng>-104.9894830</lng></location>

In applications that use device’s current location, we can test by sending different locations from console

http://developer.android.com/guide/developing/devices/emulator.html

Page 70: Getting started with android   dev and test perspective

Available console commands

Page 71: Getting started with android   dev and test perspective

IDEAS FOR TESTING

Page 72: Getting started with android   dev and test perspective

Mobile testing types Functional Testing : basic functionality of app is working

Emulator testing will cover this Usability Testing : after stable basic app is ready

Say scrolling to bottom of screen is not easy in non-touch devices Performance Testing : across devices, carriers, location

http://c0954852.cdn.cloudfiles.rackspacecloud.com/uTest_eBook_Mobile_Testing.pdf

Page 73: Getting started with android   dev and test perspective

Mobile testing methods Emulator / Simulator In House : setup lab Out sourcing :

Device ready : http://www.deviceready.com/test-android-apps-on-multiple-devices/

Droid Cloud : http://www.perfectomobile.com/portal/cms/android.html

uTest : http://www.utest.com/android-app-testing

Page 74: Getting started with android   dev and test perspective

Ideas for Testing When launching emulator / creating AVD,

we can select resolution – try to test on multiple resolutions / screen sizes

android create avd -n <name> -t <targetID> --skin WVGA800

If you were launching from Eclipse, you can select as shown

If you launch SDK Manager, you can add new AVD from there and select the resolution

http://developer.android.com/guide/developing/devices/managing-avds-cmdline.html

Page 75: Getting started with android   dev and test perspective

Ideas for testing Flow of application

Screen transitions – upon clicks / slide if permitted When doing processing, does it show a progress bar? Is it responsive? Simulate a call when app is running to see if it hangs

http://developer.android.com/guide/topics/testing/what_to_test.html

Page 76: Getting started with android   dev and test perspective

Ideas for testing Orientation change

To ensure that the app responds well in both orientation CTRL+F11 / F12

Page 77: Getting started with android   dev and test perspective

References http://en.wikipedia.org/wiki/Android_(operating_system) http://www.android.com/ http://developer.android.com/index.html http://developer.android.com/guide/developing/devices/index.html http://developer.android.com/guide/developing/devices/emulator.html http://www.android.pk/blog/general/how-to-install-apk-files-on-android-emulator/ http://developer.android.com/guide/developing/testing/index.html http://developer.android.com/guide/topics/testing/what_to_test.html http://developer.android.com/sdk/installing.html http://en.wikipedia.org/wiki/Dalvik_%28software%29 http://code.google.com/p/robotium/ : Robotium is a test framework created to

make it easy to write powerful and robust automatic black-box test cases for Android applications. With the support of Robotium, test case developers can write function, system and acceptance test scenarios, spanning multiple Android activities.

http://c0954852.cdn.cloudfiles.rackspacecloud.com/uTest_eBook_Mobile_Testing.pdf

Page 78: Getting started with android   dev and test perspective

Q and A

?