Академический Документы
Профессиональный Документы
Культура Документы
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
AndroidDevelopers A d id 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 createdbyGoogleandtheOpenHandset t db G l d th O H d t Alliance. Itisprimarilyusedtopowermobilephones. Ithasthecapabilitytomakeinroadsinmany other(nonphone)embeddedapplication markets.
4
Chapter1 2
WhatisAndroid?
Androidconsistsofacompletesetof softwarecomponentsformobiledevices ft t f bil d i including:
anoperatingsystem, middleware,and embedded key mobile applications embeddedkeymobileapplications alargemarket.
WhyAndroid?
Listenfromtheprojectcreators/developers (2.19min)
NickSears.CofounderofAndroid SteveHorowitz.EngineeringDirector St H it E i i 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
Chapter1 3
WhatisOpenHandsetAlliance?
Quotingfromwww.OpenHandsetAlliance.com page
OpenHandsetAlliance,agroupof47technology andmobilecompanieshavecometogethertoaccelerate innovationinmobileandofferconsumersaricher,less expensive,andbettermobileexperience. TogetherwehavedevelopedAndroid,thefirst complete,open,andfreemobileplatform. complete open and free mobile 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. AKM 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
TheAndroidPlatform
Again,whatdidtheysayaboutAndroid?
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 Portable music player 6. NoInternet access/ limitedaccess
Tomorrow?
12
Chapter1 6
TheMaturingMobileExperience
Iwant my2015Smartphonetoactas
Tryingtoanswer:Tomorrow? Trying to 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 GolfCaddy(ballretrievertoo) G lf C dd (b ll i ) BookReader(Idontread,Itreadstome) Car/Home/OfficeKey RemoteControl(Garage,TV,) CreditCard/DriversLicense/Passport CashonDemand Cook,housechores Psychologist/Mentor/Adviser ????
13
Androidvs.Competitors
14
Chapter1 7
15
AndroidComponents(Stack)
TheAndroidstackincludesalargearrayof featuresformobileapplications. f t f bil li ti ItwouldbeeasytoconfuseAndroidwitha generalpurposecomputingenvironment. Allofthemajorcomponentsofacomputing platformareincluded. platform are 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 (hardwaredependent) p y( 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 Inside the AndroidApplicationFramework
(about52min)
PresentedbyDanMorrill Google
AtGoogleDeveloperConference SanFrancisco 2008 Availableat:
http://sites.google.com/site/io/insidetheandroidapplicationframework htt // it l / it /i /i id th d id li ti f k
Androidisdesignedtobefast,powerful,andeasytodevelopfor.Thissession willdiscusstheAndroidapplicationframeworkindepth,showingyouthe machinerybehindtheapplicationframework. explainsthelifecycleofanandroidapk.verygood!
22
Chapter1 11
AndroidComponents
Video: AnIntroductiontoAndroid An Introduction to Android
(about52min)
23
WhyuseLinuxforaphone?
Linuxkernelisaproven coreplatform. Reliability is more important than performance when it ismoreimportantthanperformancewhenit comestoamobilephone,becausevoicecommunicationis theprimaryuseofaphone. Linuxprovidesahardwareabstractionlayer,lettingtheupper levelsremainunchangeddespitechangesintheunderlying hardware. As new accessories appear on the market drivers can be Asnewaccessories appearonthemarket,drivers canbe writtenattheLinuxleveltoprovidesupport,justasonother Linuxplatforms.
24
Chapter1 12
Dalvik VirtualMachine
User applications Userapplications,aswellascoreAndroidapplications,are ll core Android applications writteninJavaprogramminglanguageandarecompiledinto bytecodes. Androidbytecodesareinterpretedatruntimebyaprocessor knownastheDalvik virtualmachine.
25
WhyanotherJavaVirtual Machine?
Androidbytecode filesarelogicallyequivalent toJavabytecodes,buttheypermitAndroidto t J b t d b t th it A d id t
runitsapplicationsinitsownvirtualenvironmentthatis freefromSunslicensingrestrictionsand anopenplatformuponwhichGoogle,andpotentiallythe opensourcecommunity,canimproveasnecessary.
26
Chapter1 13
Dalvik VirtualMachine
Video(61min) Dalvik VMInternals D l ik VM I t l PresentedbyDanBorstein AtGoogleDeveloper 2008 Sanfrancisco Availableat:
http://www.youtube.com/watch?v=ptjedOZEXPM
27
InsideAndroid:Intents
AnimportantandrecurringthemeofAndroid developmentistheIntent. development is the Intent AnIntentinAndroiddescribeswhatyouwanttodo. Thismaylooklike
Iwanttolookupacontactrecord,or Pleaselaunchthiswebsite,or Sh ShowtheOrderConfirmationScreen. h O d C fi i S
Chapter1 14
Intents&IntentFilters
AnIntent isadeclarationofneed. AnIntent ismadeupofvariouspiecesincluding:
desiredaction orservice, data,and category ofcomponentthatshouldhandletheintentand instructionsonhowtolaunchatargetactivity.
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 Astringcontainingadditionalinformationaboutthekindofcomponentthat g y g g p 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() or Activity startActivityForResult() tolaunchanactivityorgetanexistingactivitytodosomething new(asynchronous &synchronouslyrespectively). AnIntentobjectispassedtoContext.startService() toinitiatea serviceordelivernewinstructionstoanongoingservice. AnintentcanbepassedtoContext.bindService() toestablisha connectionbetweenthecallingcomponentandatarget service.Itcanoptionallyinitiatetheserviceifit'snotalready running.
33
IntentResolution
Intentscanbedividedintotwogroups: Explicit intents designate the target component by its name Explicitintents designatethetargetcomponentbyitsname, typicallyusedforanactivitystartingasubordinateserviceor launchingasisteractivity. Implicitintents donotnameatarget(thefieldforthe componentnameisblank).Implicitintentsareoftenusedto activatecomponentsinotherapplications.Latebinding applies. applies WheneverpossibleAndroiddeliversanexplicitintenttoan instanceofthedesignatedtargetclass.
34
Chapter1 17
ExampleofIntent(1)
FollowingfragmentscallsanIntent whosejobisto invokeabuilt intask(ACTION_VIEW)andexplorethe invoke a builtin task (ACTION VIEW) and explore the Contacts availableinthephone.
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){ public void onCreate(Bundle savedInstanceState) { 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 explore a web page (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 make a phone call (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
Toinformthesystemwhichimplicit intentstheycan y p y 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:scheme="http".../> <data android type "audio/mpeg" 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,notinteractingwiththeuser, in the background not interacting with the user foranindefiniteperiodoftime. Eachserviceclassmusthaveacorresponding <service> declarationinitspackage's AndroidManifest.xml. Services can be started/stopped with Servicescanbestarted/stoppedwith
Context.startService()and Context.bindService(). stopService()andunbindService()
47
AndroidServices
Services,likeotherapplicationobjects,runin themainthreadoftheirhostingprocess. th i th d f th i h ti Thismeansthat,ifyourserviceisgoingtodo anyCPUintensive(suchasMP3playback)or blocking(suchasnetworking,RSSexchange) blocking (such as networking RSS exchange) 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 http://schemas.android.com/apk/res/android <manifest xmlns: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"/> </intent filter> </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.857:INFO/service1(767):service1firing:#4 07 01 02:50:25 857: INFO/service1(767): service1 firing : # 4
52
Chapter1 26
AndroidBroadcastReceiver
WhatisaBROADCASTRECEIVER? Ifanapplicationwantstoreceiveandrespondtoaglobalevent,suchasthe If an application wants to receive and respond to a global event such as the phoneringingoranincomingtextmessage,itmustregisterasaBroadcastReceiver. AnapplicationregisterstoreceiveIntentsbyannouncinginthe AndroidManfest.xmlfileitsIntentFilters. IfthereceiverisregisteredintheAndroidManifest.xmlfile,itdoesnothaveto berunninginordertobetriggered. Whentheglobaleventoccurs,theapplicationisstartedautomaticallyupon When the global event occurs the application is started automatically upon notificationofthetriggeringevent.Allofthishousekeepingismanagedbythe AndroidOSitself. AnapplicationmayregisteratruntimeviatheContextclasssregisterReceiver method.
53
AndroidBroadcastReceiver
BROADCASTRECEIVERandUI. Like Services BroadcastReceivers do not have a UI LikeServices,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 delivered to one receiver at a time As each receiver executes in 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 b oadcast ecei e matos.broadcastreceiver; import import import import android.content.BroadcastReceiver; android.content.Context; android.content.Intent; android.content.IntentFilter;
import android.util.Log; import android.app.Activity; po t a 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. accessible to all applications. 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 Content providers expose their data as a simple table on a 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_URI p g android.provider.Calendar.CONTENT_URI
Chapter1 34
AndroidContentProvider
QueryingaContentProvider You need three pieces of information to query a content Youneedthreepiecesofinformationtoqueryacontent provider:
TheURIthatidentifiestheprovider Thenamesofthedatafieldsyouwanttoreceive Thedatatypesforthosefields
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
70
Chapter1 35
AndroidContentProvider
Example:PostingaquerytotheContactlist(2/2) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" mlns 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 AndroidManifest.xml file (withpreciselythatname)initsroot directory. Themanifestpresentsessential informationabouttheapplicationto theAndroidsystem,informationthe the Android system information the systemmusthavebeforeitcanrunany oftheapplication'scode.
72
Chapter1 36
AndroidManifestxmlFile
Thesearetheonlylegalelements;youcannotaddyourownelementsorattributes.
<action> <activity> <activityalias> <application> <category> <data> <granturipermission> <grant uri permission> <instrumentation> <intentfilter> <manifest> <metadata>
<permission> <permissiongroup> <permissiontree> <provider> <receiver> <service> <usesconfiguration> <uses configuration> <useslibrary> <usespermission> <usessdk>
73
AndroidManifestxmlFile
Amongotherthings,themanifestdoesthefollowing: ItnamestheJavapackagefortheapplication.Thepackagenameservesasauniqueidentifier fortheapplication. for the application Itdescribesthecomponentsoftheapplication theactivities,services,broadcast receivers, andcontent providers thattheapplicationiscomposedof. Itnamestheclasses thatimplementeachofthecomponentsandpublishestheir capabilities (forexample,whichIntentmessagestheycanhandle).ThesedeclarationslettheAndroid systemknowwhatthecomponentsareandunderwhatconditionstheycanbelaunched. Itdetermineswhichprocesseswillhost application components. Itdeclareswhichpermissions theapplicationmusthaveinordertoaccessprotectedpartsof theAPIandinteractwithotherapplications. It also declares the permissions that others are required to have in order to interact with the 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"> android:versionName="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 import i 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 btnClear setOnClickListener(new OnClickListener() { // 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="@+id/absLayout" d id id "@+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="@+id/btnConvert" d id id "@+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="190px" d id l t "190 " > </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="android.intent.category.LAUNCHER" /> d id " d id i t t 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