You are on page 1of 54

mobiledevcamp androiddevelopmentworkshop

amsterdam,november2008

diegotorresmilano
diego@codtech.com
copyright2008codtechnologiesltdwww.codtech.com

Ihavealwayswishedthatmy computerwouldbeaseasyto useasmytelephone. Mywishhascometrue. Inolongerknowhowtousemy telephone.


BjarneStroustrup
copyright2008codtechnologiesltdwww.codtech.com

agenda

introductiontoandroid androidarchitecture buildingblocks yourfirstandroidapplication testingandperformance bestpractices


copyright2008codtechnologiesltdwww.codtech.com

introductiontoandroid
afterthissectionyouwill...

identifyuniquefeaturesof androidplatform compareandroidagainst otherplatforms understandandroidbuilding blocks

copyright2008codtechnologiesltdwww.codtech.com

whatisandroid?

androidisthefirstcomplete,open andfreemobileplatform developedbyOpenHandset Alliance softwarestackthanincludes


operatingsystem middleware keyapplications richsetofAPIs


Portionsofthispagearereproducedfromworkcreatedand sharedbyGoogleandusedaccordingtotermsdescribedin theCreativeCommons2.5AttributionLicense.

copyright2008codtechnologiesltdwww.codtech.com

isandroidlinux?
NO,androidisnotlinux!
androidisbasedonalinuxkernel butit'snotGNU/Linux

nonativewindowing system noglibcsupport noGNU/Linuxutilities

copyright2008codtechnologiesltdwww.codtech.com

soisandroidjava?
NO,androidisnotjava!
androidisnotanimplementation ofanyoftheJavavariants

usesthejavalanguage implementspartofthe Java5SEspecification runsonadalvikvirtual machineinsteadofJVM


copyright2008codtechnologiesltdwww.codtech.com

androidlinuxkernel
androidisbasedonalinux2.6kernel,providing rnel,p

security memorymanagement processmanagement networkstack drivermodel abstractionlayer

kernelsource:source.android.com
copyright2008codtechnologiesltdwww.codtech.com

linuxkernelenhancements
androidintroducessomelinuxkernelpatches

alarm ashmem binder powermanagement lowmemorykiller(noswapspaceavailable) logger

copyright2008codtechnologiesltdwww.codtech.com

uniqueplatformcharacteristics
androidcharacteristicsnotfoundonotherplatforms

opensource allapplicationsareequalmodel dalvikvirtualmachine

copyright2008codtechnologiesltdwww.codtech.com

othercharacteristics
interestingfeaturesaswell,buttheyaremore commonacrossothermobileplatforms

applicationframeworkenablingreuseofcomponents integratedbrowserbasedonWebKitOSSengine 3DgraphicsbasedontheOpenGLES SQLiteforstructureddatastorage mediasupportforcommonaudio,video,andstillimages camera,GPS,compass,andaccelerometer

copyright2008codtechnologiesltdwww.codtech.com

androidarchitecture

courtesyofGoogle

copyright2008codtechnologiesltdwww.codtech.com

androidbuildingblocks
afterthissectionyouwill...

recognizethefundamental buildingblocks usethesebuildingblocksto createapplications understandapplications lifecycle

copyright2008codtechnologiesltdwww.codtech.com

buildingblocks

copyright2008codtechnologiesltdwww.codtech.com

Activities

Activitiesarestacked likeadeckofcards onlyoneisvisible onlyoneisactive newactivitiesare placedontop

copyright2008codtechnologiesltdwww.codtech.com

Activitieslifecycle

rectanglesarecallbackswhere wecanimplementoperations performedonstatechanges


copyright2008codtechnologiesltdwww.codtech.com

Activitiesstates

active

atthetopofthestack lostfocusbutstillvisible canbekilledbyLMK notatthetopofthstack killedtoreclaimitsmemory


copyright2008codtechnologiesltdwww.codtech.com

paused

stopped

dropped

Views

Viewsarebasicbuildingblocks knowhowtodrawthemselves respondtoevents organizedastreestobuildupGUIs describedinXMLinlayoutresources

copyright2008codtechnologiesltdwww.codtech.com

pattern:loadlayout
androidcompilestheXMLlayoutcodethatis laterloadedincodeusuallyby
public void onCreate(Bundle savedInstanceState) { ... setContentView(R.layout.filename); ... }

copyright2008codtechnologiesltdwww.codtech.com

ViewsandViewgroups

Viewsand Viewgroupstrees buildupcomplex GUIs androidframeworkis responsiblefor


measuring layingout drawing

copyright2008codtechnologiesltdwww.codtech.com

pattern:ids
usingauniqueidinaXMLViewdefinition permitslocatingitlaterinJavacode
private View name; public void onCreate(Bundle savedInstanceState) { ... name = (View) findViewById(R.id.name); ... }

copyright2008codtechnologiesltdwww.codtech.com

Intents

IntentsareusedtomovefromActivitytoActivity describeswhattheapplicationwants provideslateruntimebinding


primary attributes attribute description action data the general action to be performed, such as VIEW, EDIT, MAIN, etc. the data to operate on, such as a person record in the contacts database, as URI

copyright2008codtechnologiesltdwww.codtech.com

intentsplayground

http://codtech.com/android/IntentPlayground.apk
copyright2008codtechnologiesltdwww.codtech.com

Services

servicesruninthebackground don'tinteractwiththeuser runonthemainthread oftheprocess iskeptrunningaslongas


isstarted hasconnections

copyright2008codtechnologiesltdwww.codtech.com

Notifications

notifytheuserabout events sentthrough NotificationManager types


persistenticon turningleds soundorvibration


copyright2008codtechnologiesltdwww.codtech.com

ConentProviders

ContentProvidersareobjectsthatcan

retrievedata storedata

dataisavailabletoallapplications onlywaytosharedataacrosspackages usuallythebackendisSQLite theyarelooselylinkedtoclients dataexposedasauniqueURI


copyright2008codtechnologiesltdwww.codtech.com

AndroidManifest.xml

controlfilethattells thesystemwhattodo andhowthetoplevel componentsare related it'sthegluethat actuallyspecifies whichIntentsyour Activitiesreceive specifiespermissions
copyright2008codtechnologiesltdwww.codtech.com

yourfirstandroid
afterthissectionyouwill...

createyourownandroidmap project designtheUI externalizeresources reacttoevents runtheapplication

copyright2008codtechnologiesltdwww.codtech.com

androidproject

copyright2008codtechnologiesltdwww.codtech.com

defaultapplication

autogenerated applicationtemplate defaultresources


icon layout strings

default AndroidManifest.xml defaultrun configuration

copyright2008codtechnologiesltdwww.codtech.com

designingtheUI
thissimpleUIdesigns contains

thewindowtitle aspinner(dropdown box)containingthe desiredlocationover themap amapdisplayingthe selectedlocation

copyright2008codtechnologiesltdwww.codtech.com

createthelayout

removeoldlayout addaRelativeLayout addaView(MapViewnot


supportedbyADT)

replaceViewby
com.google.android.m apview

changeidto mapview addaSpinnerfilling parentwidth

copyright2008codtechnologiesltdwww.codtech.com

runtheapplication

com.google.android. mapsit'sanoptional librarynotincludedby default add<uses-library


android:name="com.go ogle.android.maps" / >tomanifestas

applicationnode

copyright2008codtechnologiesltdwww.codtech.com

GoogleMapsAPIkey

checkingDDMSlogcatwefind
java.lang.IllegalArgumentException: You need to specify an API Key for each MapView.

toaccessGoogleMapsweneedakey applicationmustbesignedwiththesamekey keycanbeobtainedfromGoogle MapViewshouldinclude


android:apiKey="0GNIO0J9wdmcNm4gCV6S0nlaFE8bHa9W XXXXXX"
copyright2008codtechnologiesltdwww.codtech.com

MapActivy

checkingDDMSlogcatagain
java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity.

changebaseclasstoMapActivity fiximports addunimplementedmethods

copyright2008codtechnologiesltdwww.codtech.com

whereisthemap?

stillnomapdisplayed checkDDMSlogcat lotsofIOExceptions! someusespermissions aremissing


ACCESS_COARSE_LOCATION INTERNET

copyright2008codtechnologiesltdwww.codtech.com

finallyourmap
stillsomeproblems...

spinneriscovered
android:layout_alignPa rentTop="true"

hasnoprompt
prompt: @string/prompt

externalizeresource

copyright2008codtechnologiesltdwww.codtech.com

pattern:adapters
anAdapterobjectactsasabridgebetweenan AdapterViewandtheunderlyingdataforthatview
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.array, android.R.layout.layout); view.setAdapter(adapter); TheAdapterisalsoresponsibleformakingaViewforeachiteminthe dataset.
copyright2008codtechnologiesltdwww.codtech.com

pattern:resources
resourcesareexternalfiles(thatis,noncodefiles) thatareusedbyyourcodeandcompiledintoyour applicationatbuildtime.
<resources> <string-array name=array> <item>item</item> </string-array> </resources> res = getResources().getType(id);

copyright2008codtechnologiesltdwww.codtech.com

arrays.xml
<?xml version="1.0" encoding="UTF-8"?> <resources> <!-- No support for multidimensional arrays or complex objects yet (1.0r1) --> <string-array name="location_names"> <item>Mediamatic Duintjer</item> <item>NH Hotel</item> <item>Airport</item> </string-array> <string-array name="locations"> <item>52.363125,4.892070,18</item> <item>37.244832,-115.811434,9</item> <item>-34.560047,-58.44924,16</item> </string-array> </resources>
copyright2008codtechnologiesltdwww.codtech.com

completetheclass

createthelocationsarray
locations = getResources().getStringArray(R.array.locations);

gettheviews(idspattern)
spinner = (Spinner) findViewById(R.id.Spinner01); mapView = (MapView) findViewById(R.id.mapview);

createtheadapter
ArrayAdapter<CharSequence> adapter = ArrayAdapter. createFromResource(this, R.array.location_names, android.R.layout.simple_spinner_item); spinner.setAdapter(adapter)
copyright2008codtechnologiesltdwww.codtech.com

almostthere

mapisdisplayed spinnerisdisplayed dropdownis displayed butthere'sno selectionbutton...

adapter. setDropDownViewResource( android.R.layout. simple_spinner_dropdown_item );

copyright2008codtechnologiesltdwww.codtech.com

respondtoevents

whenanitemis selectedmapshould becenteredatthat location

spinner. setOnItemSelectedListener( new OnItemSelectedListener() { });

invoke
goToSelectedLocation(ar g2);

copyright2008codtechnologiesltdwww.codtech.com

goToSelectedLocation
protected void goToSelectedLocation(int position) { String[] loc = locations[position].split(","); double lat = Double.parseDouble(loc[0]); double lon = Double.parseDouble(loc[1]); int zoom = Integer.parseInt(loc[2]); GeoPoint p = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6)); Log.d(TAG, "Should go to " + p); mapController.animateTo(p); mapController.setZoom(zoom); }

copyright2008codtechnologiesltdwww.codtech.com

moreevents

turnmapclickable
android:clickable="true

overrideonKeyDown

switch (keyCode) { case KeyEvent.KEYCODE_I: mapController.zoomIn(); break; case KeyEvent.KEYCODE_O: mapController.zoomOut(); break; case KeyEvent.KEYCODE_S: mapView.setSatellite( !mapView.isSatellite()); break; }

copyright2008codtechnologiesltdwww.codtech.com

wedidit!

Somethingstotry

selectalocation pan zoomin zoomout togglesatellite

copyright2008codtechnologiesltdwww.codtech.com

Rememberthatthereisno codefasterthannocode
Taligent'sGuidetoDesigningPrograms

copyright2008codtechnologiesltdwww.codtech.com

testingandperformance
afterthissectionyouwill...

understandthebestpractices todevelopforandroid identifythealternativestotest units,servicesandapplications performance

copyright2008codtechnologiesltdwww.codtech.com

bestpractices

considerperformance,androidisnotadesktop avoidcreatingobjects usenativemethods prefervirtualoverinterface preferstaticovervirtual avoidinternalgetter/setters declaresconstantsfinal avoidenums


copyright2008codtechnologiesltdwww.codtech.com

testing

androidsdk1.0introduces

ActivityUnitTestCasetorunisolatedunittests ServiceTestCasetotestservices ActivityInstrumentationTestCasetorunfunctional testsofactivities

ApiDemosincludessometestsamples monkey,generatespseudorandomofuser events


copyright2008codtechnologiesltdwww.codtech.com

1000000

1500000

2000000

2500000

3000000

500000

Add a local variable

Add a member variable

Call String.length()

Call empty static native method

performance

Call empty static method

Call empty virtual method

Call empty interface method

Call Iterator:next() on a HashMap

Call put() on a HashMap

Inflate 1 View from XML

copyright2008codtechnologiesltdwww.codtech.com
Inflate 1 LinearLayout with 1 TextView Inflate 1 LinearLayout with 6 View Inflate 1 LinearLayout with 6 TextView Launch an empty activity
Time

summary

introductiontoandroid androidbuildingblocks

copyright2008codtechnologiesltdwww.codtech.com

Ifthingsseemundercontrol, you'renotgoingfastenough.
MarioAndretti

copyright2008codtechnologiesltdwww.codtech.com

thankyou androiddevelopmentworkshop
diegotorresmilano
diego@codtech.com
copyright2008codtechnologiesltdwww.codtech.com

You might also like