You are on page 1of 43

Chapter1 AndroidDevelopment Introduction

VictorMatos
ClevelandStateUniversity
Notesarebasedon:
Android A d idDevelopers D l http://developer.android.com/index.html & UnlockingAndroid byFrankAbleson,CharlieCollins,andRobi Sen. ISBN9781933988672 ManningPublications, 2009.

Chapter1 Goals
THEBIGPICTURE

1. WhatisAndroid? 2. Overviewdevelopmentenvironment

Chapter1 1

Chapter1 Resources
Androidswebpage http://www.android.com/

WhatisAndroid?
Android isanopensourcesoftwareplatform created t dby b Google G l and dth theOpen O H Handset d t Alliance. Itisprimarilyusedtopowermobilephones. Ithasthecapabilitytomakeinroadsinmany other(nonphone)embeddedapplication markets.
4

Chapter1 2

WhatisAndroid?
Androidconsistsofacompletesetof software ft components t f formobile bil devices d i including:
anoperatingsystem, middleware,and embeddedkeymobileapplications alargemarket.

WhyAndroid?
Listenfromtheprojectcreators/developers (2.19min)
NickSears.CofounderofAndroid St Horowitz. Steve H it Engineering E i i Director Di t DamMorrill.Developer Peisun Wu.EngineeringProjectManager ErickTseng.ProjectManager Iliyan Malchev.Engineer MikeCleron.SoftwareManager PerGustafsson.GraphicsDesigner. etc

http://www.youtube.com/watch?v=6rYozIZOgDk&eurl=http://www.android.com/about/&feature=player_embedd ed d

Youwillhearstatementssuchas currentlyitistoodifficulttomakenewproductsopensoftwarebringsmore innovationchoiceslowercostsmoreapplicationssuchasfamilyplanner,my taxes,understandmywifebetter,


6

Chapter1 3

WhatisOpenHandsetAlliance?
Quotingfromwww.OpenHandsetAlliance.com page
OpenHandsetAlliance,agroupof47technology andmobilecompanieshavecometogethertoaccelerate innovationinmobileandofferconsumersaricher,less expensive,andbettermobileexperience. TogetherwehavedevelopedAndroid,thefirst complete open complete, open,andfreemobileplatform. platform Wearecommittedtocommerciallydeployhandsetsand servicesusingtheAndroidPlatform.

OpenHandsetAllianceMembers
Operators
ChinaMobile ChinaUnicom KDDICorp. NTTDoCoMo SprintNextel TMobile TelecomItalia Telefnica Vodafone Softbank Ericsson SoftwareCo. AscenderCorp. eBay Esmertec Google LivingImage NMSComm. NuanceComm. PacketVideo SkyPop SONiVOX Borqs

Commercializat.
Aplix Noser Engineering AstonishingTribe WindRiverSystems OmronSoftware Teleca

Semiconductor
Audience BroadcomCorp. IntelCorp. MarvellTech. Group Nvidia Corp. Qualcomm SiRF Tech.Holdings Synaptics TexasInstr. AKMSemicond. Semicond ARM Atheros Comm ... EMP

HandsetManf
ACER ASUS HTC LG Motorola Samsung ASUSTek Garmin Huawei Tech LG Samsung SonyEricsson Toshiba

Chapter1 4

SeeAndroidDevelopers
http://www.youtube.com/watch?v=7Y4thikvOM

Shortvideo(4min.) Sh i Dave Showing D Bort B t andDanBorstein, twomembersofthe AndroidOpenSource Projecttalkabout theproject.

TheAndroidPlatform
Again,whatdidtheysayaboutAndroid?

Androidisasoftware environmentbuiltformobile devices. Itisnot ahardwareplatform. Androidincludes:


LinuxkernelbasedOS, arichUI, telephonefunctionality, enduserapplications, codelibraries, applicationframeworks, multimediasupport,...

UserapplicationsarebuiltforAndroidinJava.
10

Chapter1 5

AndroidsContext:MobileMarketPlayer$
Stakeholders: Mobilenetwork operators want tolockdowntheirnetworks, controllingandmeteringtraffic. Device manufacturers wantto differentiatethemselveswith features,reliability,andprice points. Software vendors wantcomplete accesstothehardwaretodeliver cuttingedgeapplications.

Operators

Device Manufacturers

Software Vendors

11

TheMaturingMobileExperience
Electronictoolsofatypicalbusinesswarrior

Notsolongago 1. Phone 2. Pager 3. PDAOrganizer 4. Laptop 5 Portablemusicplayer 5. 6. NoInternet access/ limitedaccess


Tomorrow?

Today 1. Smartphone 2. Laptop(perhaps!)

12

Chapter1 6

TheMaturingMobileExperience
Iwant my2015Smartphonetoactas
Tryingtoanswer: answer Tomorrow?
1. 2. 3. 4. 5. 6. 7. 8. 9. 10 10. 11. 12. 13. 14. 15. 16. 17. 18. Phone Pager PDAOrganizer HighQualityCamera(still&video) Portablemusicplayer Portable TV/VideoPlayer/Radio Laptop PlayStation GPS G lfCaddy Golf C dd (ball (b llretriever i too) ) BookReader(Idontread,Itreadstome) Car/Home/OfficeKey RemoteControl(Garage,TV,) CreditCard/DriversLicense/Passport CashonDemand Cook,housechores Psychologist/Mentor/Adviser ????
13

Androidvs.Competitors

1.AppleInc. 2.Microsoft 3.Nokia 4.Palm 5 ResearchInMotion 5.Research 6.Symbian

14

Chapter1 7

TheSizeof theMobile Market


http://gizmodo.com/5489036 / ll h /cellphone overshare h [seeappendix]

15

AndroidComponents(Stack)
TheAndroidstackincludesalargearrayof f t features for f mobile bil applications. li ti ItwouldbeeasytoconfuseAndroidwitha generalpurposecomputingenvironment. Allofthemajorcomponentsofacomputing platformareincluded. included

16

Chapter1 8

AndroidComponents
Applicationframework enablingreuseandreplacementofcomponents Dalvik virtualmachine optimizedformobiledevices Integratedbrowser basedontheopensourceWebKit engine Optimizedgraphics poweredbyacustom2Dgraphicslibrary;3Dgraphics basedontheOpenGLESspecification(hardwareaccelerationoptional) SQLite forstructureddatastorage Mediasupport forcommonaudio,video,andstillimageformats(MPEG4, H.264,MP3,AAC,AMR,JPG,PNG,GIF) GSMTelephony p y( (hardwaredependent) p ) Bluetooth,EDGE,3G,4G,andWiFi (hardwaredependent) Camera,GPS,compass,andaccelerometer (hardwaredependent) Richdevelopmentenvironment includingadeviceemulator,toolsfor debugging,memoryandperformanceprofiling,andaplugin forthe EclipseIDE
17

AndroidComponents

18

Chapter1 9

AndroidComponents
Video1/3:AndroidsArchitecture PresentedbyMikeCleron,GoogleCorp.(13min)

Availableat:http://www.youtube.com/watch?v=QBGfUs9mQYY

19

AndroidComponents
Video2/3:ApplicationsLifeCycle PresentedbyMikeCleron,GoogleCorp.(8min)

Availableat:http://www.youtube.com/watch?v=fL6gSd4ugSI&feature=channel

20

Chapter1 10

AndroidComponents
Video3/3:AndroidsAPI PresentedbyMikeCleron,GoogleCorp.(7min)

Availableat:http://www.youtube.com/watch?v=MPukbH6DlY&feature=channel

21

AndroidApplicationFramework
Video: Insidethe AndroidApplicationFramework
(about52min)

PresentedbyDanMorrill Google
AtGoogleDeveloperConference SanFrancisco 2008 Availableat:

htt // it http://sites.google.com/site/io/inside l / it /i /i id the th android d idapplication li ti framework f k


Androidisdesignedtobefast,powerful,andeasytodevelopfor.Thissession willdiscusstheAndroidapplicationframeworkindepth,showingyouthe machinerybehindtheapplicationframework. explainsthelifecycleofanandroidapk.verygood!
22

Chapter1 11

AndroidComponents
Video: AnIntroductiontoAndroid
(about52min)

PresentedbyJasonChen Google AtGoogleDeveloperConference SanFrancisco 2008 Availableat:


http://www youtube com/watch?v x1ZZR3p_w8 http://www.youtube.com/watch?v=x1ZZ R3p w8

23

WhyuseLinuxforaphone?
Linuxkernelisaproven coreplatform. Reliability ismoreimportantthanperformancewhenit comestoamobilephone,becausevoicecommunicationis theprimaryuseofaphone. Linuxprovidesahardwareabstractionlayer,lettingtheupper levelsremainunchangeddespitechangesintheunderlying hardware. Asnewaccessories appearonthemarket, market drivers canbe writtenattheLinuxleveltoprovidesupport,justasonother Linuxplatforms.

24

Chapter1 12

Dalvik VirtualMachine
Userapplications,aswell llascoreAndroidapplications,are writteninJavaprogramminglanguageandarecompiledinto bytecodes. Androidbytecodesareinterpretedatruntimebyaprocessor knownastheDalvik virtualmachine.

25

WhyanotherJavaVirtual Machine?
Androidbytecode filesarelogicallyequivalent t J to Javabytecodes, b t d but b tth theypermit itA Android d idt to
runitsapplicationsinitsownvirtualenvironmentthatis freefromSunslicensingrestrictionsand anopenplatformuponwhichGoogle,andpotentiallythe opensourcecommunity,canimproveasnecessary.

26

Chapter1 13

Dalvik VirtualMachine
Video(61min) D l ik VMInternals Dalvik I t l PresentedbyDanBorstein AtGoogleDeveloper 2008 Sanfrancisco Availableat:
http://www.youtube.com/watch?v=ptjedOZEXPM

27

InsideAndroid:Intents
AnimportantandrecurringthemeofAndroid developmentistheIntent. AnIntentinAndroiddescribeswhatyouwanttodo. Thismaylooklike
Iwanttolookupacontactrecord,or Pleaselaunchthiswebsite,or Show Sh the h Order O d Confirmation C fi i Screen. S

Intentsareimportantbecausetheyfacilitate navigationandrepresentthemostimportantaspect ofAndroidcoding.


28

Chapter1 14

Intents&IntentFilters
AnIntent isadeclarationofneed. AnIntent ismadeupofvariouspiecesincluding:
desiredaction orservice, data,and category ofcomponentthatshouldhandletheintentand instructionsonhowtolaunchatargetactivity.

A AnIntentFilter I t tFilt is i atrigger, ti ad declaration l ti of fcapability bilit and d interestinofferingassistancetothoseinneed. AnIntentFilter maybegenericorspecificwithrespectto whichIntentsitofferstoservice.
29

Intents&IntentFilters
Anintent isanabstractdescriptionofanoperationtobe performed. Itsmostsignificantuseisinthelaunchingofactivities,where itcanbethoughtofasthegluebetweenactivities. Theprimarypiecesofinformationinanintentare:
Action Thegeneralactiontobe performed,suchas: ACTION_VIEW, ACTION_EDIT, ACTION_MAIN,etc. Data Thedatatooperateon,suchas apersonrecordinthecontacts database,expressedasaUri.

30

Chapter1 15

Intents&IntentFilters
SomeexamplesofIntentsaction/datapairsare:
ACTION_VIEW content://contacts/1 Displayinformationaboutthe personwhoseidentifieris"1". ACTION_DIAL content://contacts/1 Displaythephonedialerwiththe personfilledin. ACTION_VIEW tel:123 Displaythephonedialerwiththegivennumber filledin ACTION_DIAL tel:123 Displaythephonedialerwiththegivennumber filledin. ACTION_EDIT content://contacts/1 Editinformationabouttheperson whoseidentifieris"1". ACTION_VIEW content://contacts/ Displayalistofpeople,whichthe usercanbrowsethrough.
31

DissectingIntents
1. Componentname Thenameofthecomponentthatshouldhandletheintent(for example"com.example.project.app.MyActivity1"). Action Astringnamingtheactiontobeperformed or,inthecaseofbroadcast intents,theactionthattookplaceandisbeingreported(forexample:ACTION_VIEW, ACTION_CALL,ACTION_TIMEZONE_CHANGED,). Data TheURIofthedatatobeactedonandtheMIMEtypeofthatdata(forexample tel:/216 555-1234 , "http://maps.google.com,...). Category g y Astring gcontaining gadditionalinformationaboutthekindofcomponent p that shouldhandletheintent(forexampleCATEGORY_BROWSABLE, CATEGORY_LAUNCHER, ). Extras Keyvaluepairs foradditionalinformationthatshouldbedeliveredtothe componenthandlingtheintent. Flags ofvarioussorts.

2.

3.

4.

5.

6.

32

Chapter1 16

DeliveringIntents
AnIntentobjectispassedto Context startActivity() orActivity.startActivityForResult() Context.startActivity() Activity startActivityForResult() tolaunchanactivityorgetanexistingactivitytodosomething new(asynchronous &synchronouslyrespectively). AnIntentobjectispassedtoContext.startService() toinitiatea serviceordelivernewinstructionstoanongoingservice. AnintentcanbepassedtoContext.bindService() toestablisha connectionbetweenthecallingcomponentandatarget service.Itcanoptionallyinitiatetheserviceifit'snotalready running.

33

IntentResolution
Intentscanbedividedintotwogroups: Explicitintents designatethetargetcomponentbyitsname, name typicallyusedforanactivitystartingasubordinateserviceor launchingasisteractivity. Implicitintents donotnameatarget(thefieldforthe componentnameisblank).Implicitintentsareoftenusedto activatecomponentsinotherapplications.Latebinding applies. applies WheneverpossibleAndroiddeliversanexplicitintenttoan instanceofthedesignatedtargetclass.
34

Chapter1 17

ExampleofIntent(1)
FollowingfragmentscallsanIntent whosejobisto invokeabuiltintask(ACTION_VIEW ACTION VIEW)andexplorethe Contacts availableinthephone.

Intent myIntent = new Intent( Intent.ACTION_VIEW, Uri.parse("content://contacts/people")); startActivity(myIntent);


35

ExampleofIntent(1)
Intentuses ACTION_VIEW tosee Contacts.

36

Chapter1 18

ExampleofIntent(1)
CompletecodetoseeContacts.
packagematos.cis493; importandroid.app.Activity; importandroid.content.Intent; importandroid.net.Uri; importandroid.os.Bundle; publicclassAndDemo1extendsActivity{ /**showcontactlist*/ @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); IntentmyIntent =newIntent( Intent.ACTION_VIEW,Uri.parse( "content://contacts/people")); startActivity(myIntent); } }
37

ExampleofIntent(2)
FollowingIntent usesbuiltintask(ACTION_VIEW)to exploreawebpage (seenewUrivalue)
Intent myIntent = new Intent( Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(myIntent);

38

Chapter1 19

ExampleofIntent(3)
FollowingIntent usesbuiltintask(ACTION_VIEW)to makeaphonecall (seenewUrivalue)
Intent myIntent = new Intent( Intent.ACTION_VIEW, Uri.parse("tel:/216 555-1234")); startActivity(myIntent);

39

IntentFilters
TheIntentFilter definestherelationshipbetweenthe Intentandtheapplication. IntentFilters canbespecifictothedataportionof theIntent,theactionportion,orboth. IntentFilters alsocontainafieldknownasacategory. Acategoryhelpsclassifytheaction. Forexample,thecategorynamed CATEGORY_LAUNCHER instructsAndroidthattheActivitycontainingthis IntentFilter shouldbevisibleinthehomescreen.
40

Chapter1 20

IntentFilters
WhenanIntent isdispatched,thesystemevaluates theavailableActivities,Services,andregistered BroadcastReceivers androutestheIntenttothemost appropriate recipient(seenextFigure).

41

IntentFilters

42

Chapter1 21

IntentFilters
Toinformthesystem y whichimplicit p intentsthey ycan handle,activities,services,andbroadcastreceivers can haveoneormoreintentfilters. Eachfilterdescribesacapabilitythatthecomponentis willingtoreceive. Anexplicit intentisalwaysdeliveredtoitstarget,nomatter whatitcontains;thefilterisnotconsulted. Butanimplicitintentisdeliveredtoacomponentonlyifit canpassthroughoneofthecomponent'sfilters.
43

IntentFilters
IntentFilters areoftendefinedinanapplications pp AndroidManifest.xmlwiththe<intentfilter> tag.
<intentfilter...> <actionandroid:name="codeandroid.intent.action.MAIN"/> <categoryandroid:name="codeandroid.intent.category.LAUNCHER"/> <categoryandroid:name="android.intent.category.BROWSABLE"/> <dataandroid:type="video/mpeg"android:scheme="http".../> <dataandroid:type="audio/mpeg" android type "audio/mpeg"android:scheme="http" android scheme "http".../> ... </intentfilter>

44

Chapter1 22

AndroidApplications
EachAndroid applicationrunsinitsownLinux process. Anapplicationconsistsofacombinationofsoftware componentsincluding:
Activities Services BroadcastReceivers ContentProviders

45

AndroidApplications
Structureof atypical t i l Android Application

46

Chapter1 23

AndroidServices
AService isanapplicationcomponentthatruns inthebackground, background notinteractingwiththeuser, user foranindefiniteperiodoftime. Eachserviceclassmusthaveacorresponding <service> declarationinitspackage's AndroidManifest.xml. Servicescanbestarted/stoppedwith
Context.startService()and Context.bindService(). stopService()andunbindService()
47

AndroidServices
Services,likeotherapplicationobjects,runin th main the i thread th dof ftheir th i hosting h ti process. Thismeansthat,ifyourserviceisgoingtodo anyCPUintensive(suchasMP3playback)or blocking(suchasnetworking, networking RSSexchange) operations,itshouldspawnitsownthreadin whichtodothatwork
48

Chapter1 24

AndroidServices
Service1Class package matos.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class Service1 extends Service implements Runnable { private int counter = 0; @Override public void onCreate() { super.onCreate(); Thread aThread = new Thread(this); aThread.start(); } public void run() { while (true) { try y { Log.i("service1", "service1 firing : # " + counter++); Thread.sleep(10000); //this is where the heavy-duty computing occurs } catch (Exception ee) { Log.e("service1", ee.getMessage()); } } } @Override public IBinder onBind(Intent intent) { return null; } }

49

AndroidServices
//Service1Driver packagematos.service; importandroid.app.Activity; d d importandroid.content.Intent; importandroid.os.Bundle; publicclassService1Driver extendsActivity{ @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); //invokingtheservice Intentservice1Intent=newIntent(this,Service1.class); startService(service1Intent); //dosomeworkhere. } }//Service1Driver
50

Chapter1 25

AndroidServices
Service1DemoManifest
<?xmlversion="1.0"encoding="utf8"?> <manifestxmlns:android xmlns:android="http://schemas.android.com/apk/res/android" http://schemas.android.com/apk/res/android package="matos.service" android:versionCode="1" android:versionName="1.0"> <applicationandroid:icon="@drawable/icon"android:label="@string/app_name"> <activityandroid:name=".Service1Driver" android:label="@string/app_name"> <intentfilter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intentfilter> </activity> <serviceandroid:name="Service1"android:enabled="true"> </service> </application> <usessdk android:minSdkVersion="3"/> </manifest>
51

AndroidServices
Debugging LogCat
070102:49:46.097:INFO/ActivityManager(583):Displayedactivitymatos.service /.Service1Driver 070102:49:51.277:DEBUG/dalvikvm(724):GCfreed1575objects/81280bytesin138ms 070102:49:55.831:INFO/service1(767):service1firing:#1 070102:50:05.839:INFO/service1(767):service1firing:#2 070102:50:15.847:INFO/service1(767):service1firing:#3 070102:50:25 02:50:25.857: 857:INFO/service1(767):service1firing:#4

52

Chapter1 26

AndroidBroadcastReceiver
WhatisaBROADCASTRECEIVER? Ifanapplicationwantstoreceiveandrespondtoaglobalevent,suchasthe phoneringingoranincomingtextmessage,itmustregisterasaBroadcastReceiver. AnapplicationregisterstoreceiveIntentsbyannouncinginthe AndroidManfest.xmlfileitsIntentFilters. IfthereceiverisregisteredintheAndroidManifest.xmlfile,itdoesnothaveto berunninginordertobetriggered. Whentheglobaleventoccurs occurs,theapplicationisstartedautomaticallyupon notificationofthetriggeringevent.Allofthishousekeepingismanagedbythe AndroidOSitself. AnapplicationmayregisteratruntimeviatheContextclasssregisterReceiver method.
53

AndroidBroadcastReceiver
BROADCASTRECEIVERandUI. LikeServices Services,BroadcastReceivers donothaveaUI. Ofevenmoreimportance,thecoderunningintheonReceive methodofaBroadcastReceiver shouldmakenoassumptions aboutpersistenceorlongrunningoperations. IftheBroadcastReceiver requiresmorethanatrivialamount ofcodeexecution,itisrecommendedthatthecodeinitiatea requesttoaService tocompletetherequestedfunctionality.

54

Chapter1 27

AndroidBroadcastReceiver
BROADCASTRECEIVER
SomeActivity sendBroadcast() BroadcastReceiver onReceive()

BroadcastReceiver onReceive()

BroadcastReceiver onReceive()
55

AndroidBroadcastReceiver
Intentsvs.Broadcasts
StartinganActivitywithanIntentisaforeground operationthatmodifieswhattheuseriscurrently interactingwith. BroadcastinganIntentisabackground operation thattheuserisnotnormallyawareof.

56

Chapter1 28

AndroidBroadcastReceiver
TypeofBroadcasts
Therearetwomajorclassesofbroadcaststhatcanbereceived: Normalbroadcasts (sentwithsendBroadcast)arecompletely asynchronous.Allreceiversofthebroadcastareruninanundefined order,oftenatthesametime.Thisismoreefficient,butmeansthat receiverscannotusetheresultorabortAPIsincludedhere. Orderedbroadcasts (sentwithsendOrderedBroadcast)are deliveredtoonereceiveratatime.Aseachreceiverexecutesin turn,itcanpropagatearesulttothenextreceiver,oritcan completelyabortthebroadcastsothatitwon'tbepassedtoother receivers.Theorderreceiversrunincanbecontrolledwiththe android:priority attributeofthematchingintentfilter;receivers withthesameprioritywillberuninanarbitraryorder.
57

AndroidBroadcastReceiver
BroadcastReceiverLifeCycle
AprocessthatiscurrentlyexecutingaBroadcastReceiver (thatis, currentlyrunningthecodeinitsonReceive(Context,Intent) method)is consideredtobeaforegroundprocessandwillbekeptrunningbythe systemexceptundercasesofextremememorypressure. OnceyoureturnfromonReceive(),theBroadcastReceiver isnolonger active,anditshostingprocessisonlyasimportantasanyotherapplication componentsthatarerunninginit. ThismeansthatforlongerrunningoperationsyouwilloftenuseaService inconjunctionwithaBroadcastReceiver tokeepthecontainingprocess activefortheentiretimeofyouroperation.

58

Chapter1 29

AndroidBroadcastReceiver
BroadcastReceiverExample(1/5).InterceptarrivingSMS
package matos.broadcastreceiver; matos b oadcast ecei e import import import import android.content.BroadcastReceiver; android.content.Context; android.content.Intent; android.content.IntentFilter;

import android.util.Log; import po t a android.app.Activity; d o d app ct ty; import android.os.Bundle; public class MySMSMailBox extends Activity { // intercepts reception of new text-messages

59

AndroidBroadcastReceiver
BroadcastReceiverExample(2/5).InterceptarrivingSMS
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // define instance of local broadcast receiver MySMSMailBoxReceiver mySmsReceiver = new MySMSMailBoxReceiver(); // receiver's filter will accept event: ...SMS_RECEIVED IntentFilter filter = new IntentFilter( "android.provider.Telephony.SMS_RECEIVED"); // tell Android OS this receiver is ready to go

registerReceiver(mySmsReceiver, filter);
}
60

Chapter1 30

AndroidBroadcastReceiver
BroadcastReceiverExample(3/5).InterceptarrivingSMS
// this is the custom made broadcast receiver. Its onReceive method // is fired when the filter matches the SMS_RECEIVED event public class MySMSMailBoxReceiver extends BroadcastReceiver { public static final String tag = "<<< MySMSMailBox >>>"; @Override public void onReceive(Context context, Intent intent) { Log.i(tag, "onReceive"); // checking global event signaling arrival of text-message if (intent.getAction().equals( "android.provider.Telephony.SMS_RECEIVED")) { Log i(tag, Log. i(tag "Found our SMS Event!"); // you have intercepted the SMS // do something interesting with it. Bye! } }// onReceive } // BroadcastReceiver }
61

AndroidBroadcastReceiver
BroadcastReceiverExample(4/5).InterceptarrivingSMS

62

Chapter1 31

AndroidBroadcastReceiver
BroadcastReceiverExample(5/5).InterceptarrivingSMS
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="matos.broadcastreceiver" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MySMSMailBox" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> / i i </application> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <receiver android:name="MySMSMailBoxReceiver" > <intent-filter> <action android:name = "android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> <uses-sdk android:minSdkVersion="3" /> </manifest>

63

AndroidContentProvider
Contentproviders store andretrieve dataandmakeit accessibletoallapplications. TheyaretheonlywaytosharedataacrossAndroid applications.There'snocommonstorageareathatallAndroid packagescanaccess. Androidshipswithanumberofcontentprovidersfor commondatatypes(audio,video,images,personalcontact information,andsoon).

64

Chapter1 32

AndroidContentProvider
ContentProviders areadatalayerprovidingdataabstraction foritsclientsandcentralizingstorageandretrievalroutinesin asingleplace. AContentProvider mayprovidedatatoanActivityorService inthesameapplicationsspaceaswellasanActivityor Servicecontainedinotherapplications. AContentProvider mayuseanyformofdatastorage mechanismavailableontheAndroidplatform,includingfiles, SQLite databases,orevenamemorybasedhashmapifdata persistenceisnotrequired.
65

AndroidContentProvider

66

Chapter1 33

AndroidContentProvider
Thedatamodel Contentprovidersexposetheirdataasasimpletableona databasemodel,whereeachrow isarecordandeachcolumn isdataofaparticulartypeandmeaning. Forexample,informationaboutpeopleandtheirphone numbersmightbeexposedasfollows:

67

AndroidContentProvider
URIs EachcontentproviderexposesapublicURIthatuniquelyidentifiesitsdataset. Acontentproviderthatcontrolsmultipledatasets(multipletables)exposesa separateURIforeachone. AllURIsforprovidersbeginwiththestring"content://". AndroiddefinesCONTENT_URIconstantsforalltheprovidersthatcomewiththe platform.Forexample
android.provider.Contacts.Phones.CONTENT_URI android.provider.Contacts.Photos.CONTENT_URI android.provider.CallLog.Calls.CONTENT p g _URI android.provider.Calendar.CONTENT_URI

TheContentResolver methodtakesanURIasitsfirstargument.It'swhatidentifies whichprovidertheContentResolver shouldtalktoandwhichtableoftheprovider isbeingtargeted.


68

Chapter1 34

AndroidContentProvider
QueryingaContentProvider Youneedthreepiecesofinformationtoqueryacontent provider:
TheURIthatidentifiestheprovider Thenamesofthedatafieldsyouwanttoreceive Thedatatypesforthosefields

Ifyou'requeryingaparticularrecord,youalsoneedtheIDfor thatrecord. record AqueryreturnsaCursor objectthatcanmovefromrecordto recordandcolumntocolumntoreadthecontentsofeach field.Ithasspecializedmethodsforreadingeachtypeofdata.


69

AndroidContentProvider
Example:PostingaquerytotheContactlist(1/2)
package matos.cis493; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.widget.EditText; import android.widget.Toast; import android.provider.Contacts.People; import android.content.ContentUris; import android.database.Cursor; public class AndDemo1 extends Activity { /** queries contact list */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Use the ContentUris method to produce the base URI for the contact with _ID == 23. Uri myPerson1 = ContentUris.withAppendedId(People.CONTENT_URI, 23); // use the "people" content provider to explore all your contacts

Uri myPerson2 = Uri.parse("content://contacts/people");


// Then query for this specific record using method: managedQuery // args: (Uri uri, String[] projection, String selection, // String[] selectionArgs, String sortOrder)

Cursor cur = managedQuery(myPerson2, null, null, null, null);


// do something with the cursor here } }

70

Chapter1 35

AndroidContentProvider
Example:PostingaquerytotheContact list(2/2) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android= mlns android "http://schemas.android.com/apk/res/android" "http //schemas android com/apk/res/android" package="matos.cis493" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AndDemo1" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="3" /> <uses-permission android:name="android.permission.READ_CONTACTS"> </uses-permission> </manifest>

71

AndroidManifestxmlFile
Everyapplicationmusthavean AndroidManifest.xmlfile (withpreciselythatname)initsroot directory. Themanifestpresentsessential informationabouttheapplicationto theAndroidsystem, system informationthe systemmusthavebeforeitcanrunany oftheapplication'scode.

72

Chapter1 36

AndroidManifestxmlFile
Thesearetheonlylegalelements;youcannotaddyourownelementsorattributes.

<action> <activity> <activityalias> <application> <category> <data> <granturipermission> <instrumentation> <intentfilter> <manifest> <metadata>

<permission> <permissiongroup> <permissiontree> <provider> <receiver> <service> <usesconfiguration> <useslibrary> <usespermission> <usessdk>

73

AndroidManifestxmlFile
Amongotherthings,themanifestdoesthefollowing: ItnamestheJavapackagefortheapplication.Thepackagenameservesasauniqueidentifier fortheapplication. application Itdescribesthecomponentsoftheapplication theactivities,services,broadcast receivers, andcontent providers thattheapplicationiscomposedof. Itnamestheclasses thatimplementeachofthecomponentsandpublishestheir capabilities (forexample,whichIntentmessagestheycanhandle).ThesedeclarationslettheAndroid systemknowwhatthecomponentsareandunderwhatconditionstheycanbelaunched. Itdetermineswhichprocesseswillhost application components. Itdeclareswhichpermissions theapplicationmusthaveinordertoaccessprotectedpartsof theAPIandinteractwithotherapplications. Italsodeclaresthepermissionsthatothersarerequiredtohaveinordertointeractwiththe application'scomponents. ItliststheInstrumentation classesthatprovideprofilingandotherinformationasthe applicationisrunning.Thesedeclarationsarepresentinthemanifestonlywhilethe applicationisbeingdevelopedandtested;they'reremovedbeforetheapplicationis published. ItdeclarestheminimumleveloftheAndroidAPIthattheapplicationrequires. Itliststhelibraries thattheapplicationmustbelinkedagainst.
74

Chapter1 37

AndroidManifestxmlFile
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="matos.earthquake" android:versionCode="1" android:versionName="1.0.0"> "1 0 0"> <application android:icon="@drawable/yellow_circle" android:label="@string/app_name">

<activity android:name=".AndQuake" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SatelliteMapping"> </activity>

<service android:name="AndQuakeService" android:enabled="true" > </service> <receiver android:name="AndQuakeAlarmReceiver" > <intent-filter> <action android:name = "ALARM_TO_REFRESH_QUAKE_LIST"/> </intent-filter> </receiver> </application> <uses-library android:name="com.google.android.maps" /> <uses-permission android:name="android.permission.INTERNET" /> </manifest>

75

Example.Currencyconverter
Implementingasimplecurrencyconverter: USD Euro Colon(CR)
Note. Naiveimplementationusingtherates
1CostaRicanColon=0.001736U.S.dollars 1Euro=1.39900U.S.dollars

76

Chapter1 38

Example.Currencyconverter

77

Example.Currencyconverter
package matos.currencyconvereter; import i import import import import import import android.app.Activity; android.os.Bundle; d id dl android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.EditText; android.widget.Toast;

public class Currency1 extends Activity { // naive currency converter from USD to Euros & Colones

final double EURO2USD = 1.399; final double COLON2USD = 0.001736; // GUI widgets Button btnConvert; Button btnClear; EditText txtUSDollars; EditText txtEuros; EditText txtColones;

78

Chapter1 39

Example.Currencyconverter
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // bind local controls to GUI widgets txtUSDollars = (EditText)findViewById(R.id.txtUSDollars); txtUSDollars.setHint("Enter US dollars"); txtEuros = (EditText)findViewById(R.id.txtEuros); txtColones = (EditText)findViewById(R.id.txtColones); // attach click behavior to buttons btnClear = (Button)findViewById(R.id.btnClear); btnClear setOnClickListener(new OnClickListener() { btnClear.setOnClickListener( // clear the text boxes @Override public void onClick(View v) { txtColones.setText(""); txtEuros.setText(""); txtUSDollars.setText(""); } }); 79

Example.Currencyconverter
// do the conversion from USD to Euros and Colones btnConvert = (Button) findViewById(R.id.btnConvert); btnConvert.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { String usdStr = txtUSDollars.getText().toString(); double usd = Double.parseDouble( usdStr ); String euros = String.valueOf( usd / EURO2USD ); String colones = String.valueOf( usd / COLON2USD ); txtEuros.setText(euros); txtColones.setText(colones); } catch (Exception e) { Toast makeText(v.getContext(), Toast. makeText(v getContext() "Invalid data - try again" , Toast.LENGTH_SHORT).show(); } } });// setOnClick... }// onCreate }// class 80

Chapter1 40

Example.Currencyconverter

81

Example.Currencyconverter
Resource:res/layout/main.xml(1/2)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout LinearLayout android:id="@+id/widget47" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/an droid" > <TextView android:id="@+id/caption1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Currency Converter v0.01" android:textSize="18sp" android:textStyle="bold" > </TextView> <TextView android:id="@+id/greenFiller1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#ff006666" > </TextView> <AbsoluteLayout android:id= d id id "@+id/absLayout" "@+id/ b L t" android:layout_width="316px" android:layout_height="308px" android:background="#ff003399" > <TextView android:id="@+id/usdCaption" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="US Dollars" android:layout_x="40px" android:layout_y="15px" > </TextView> <EditText android:id="@+id/txtUSDollars" android:layout_width="150px" android:layout_height="wrap_content" android:layout_x="130px" android:layout_y="10px" > </TextView>

82

Chapter1 41

Example.Currencyconverter
Resource:res/layout/main.xml(2/2)
<EditText android:id="@+id/txtEuros" android:id @ id/txtEuros android:layout_width="150px" android:layout_height="wrap_content android:layout_x="130px" android:layout_y="70px" > </EditText> <TextView android:id="@+id/colonCaption" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Colones(CR)" android:layout_x="40px" android:layout_y="135px" > </TextView> <EditText android:id="@+id/txtColones" android:layout_width="150px" android:layout_height="wrap_content android:layout_x="130px" android:layout_y="130px" > </EditText> <Button android:id= d id id "@+id/btnConvert" "@+id/bt C t" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Convert " android:layout_x="10px" android:layout_y="190px" > </Button> <Button android:id="@+id/btnClear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Clear " android:layout_x="90px" android:layout_y= d id l t "190 " "190px" > </Button> </AbsoluteLayout> </LinearLayout>

83

Example.Currencyconverter
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="matos.currencyconvereter" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Currency1" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name= d id " d id i t t "android.intent.category.LAUNCHER" t LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="3" /> </manifest>

84

Chapter1 42

AdditionalResources
GoogleDeveloperConference SanFrancisco 2009 Webpage:http://code.google.com/events/io/

85

Chapter1 43

You might also like