You are on page 1of 43

Chapter1 1

Chapter1
AndroidDevelopment
Introduction
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
A d id D l Android Developers
http://developer.android.com/index.html
&
UnlockingAndroid
by Frank Ableson,Charlie Collins,and Robi Sen.
ISBN9781933988672
ManningPublications,2009.
1
Chapter1 Goals
THEBIGPICTURE
1. WhatisAndroid?
2. Overviewdevelopmentenvironment
2
Chapter1 2
Chapter1 Resources
Androidswebpage
http://www.android.com/
3
WhatisAndroid?
Android isanopensourcesoftwareplatform
t d b G l d th O H d t createdbyGoogleandtheOpenHandset
Alliance.
Itisprimarilyusedtopowermobilephones.
Ithasthecapabilitytomakeinroadsinmany
other(nonphone)embeddedapplication
markets.
4
Chapter1 3
WhatisAndroid?
Androidconsistsofacompletesetof
ft t f bil d i softwarecomponentsformobiledevices
including:
anoperatingsystem,
middleware,and
embedded key mobile applications embeddedkeymobileapplications
alargemarket.
5
WhyAndroid?
Listenfromtheprojectcreators/developers (2.19min)
NickSears.CofounderofAndroid
St H it E i i Di t SteveHorowitz.EngineeringDirector
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
d ed
Youwillhearstatementssuchas
currentlyitistoodifficulttomakenewproductsopensoftwarebringsmore
innovationchoiceslowercostsmoreapplicationssuchasfamilyplanner,my
taxes,understandmywifebetter,
6
Chapter1 4
WhatisOpenHandsetAlliance?
Quotingfromwww.OpenHandsetAlliance.com
page
OpenHandsetAlliance,agroupof47technology
andmobilecompanieshavecometogethertoaccelerate
innovationinmobileandofferconsumersaricher,less
expensive,andbettermobileexperience.
TogetherwehavedevelopedAndroid,thefirst
complete open and free mobile platform complete,open,andfreemobileplatform.
Wearecommittedtocommerciallydeployhandsetsand
servicesusingtheAndroidPlatform.
7
OpenHandsetAllianceMembers
Operators SoftwareCo. Commercializat. Semiconductor HandsetManf
ChinaMobile AscenderCorp. Aplix Audience ACER
ChinaUnicom
KDDICorp.
NTTDoCoMo
SprintNextel
TMobile
TelecomItalia
Telefnica
Vodafone
Softbank
eBay
Esmertec
Google
LivingImage
NMSComm.
NuanceComm.
PacketVideo
SkyPop
SONiVOX
Noser Engineering
AstonishingTribe
WindRiverSystems
OmronSoftware

Teleca
BroadcomCorp.
IntelCorp.
MarvellTech.
Group
Nvidia Corp.
Qualcomm
SiRF Tech.Holdings
Synaptics
TexasInstr.
AKM Semicond
ASUS
HTC
LG
Motorola
Samsung
ASUSTek
Garmin
Huawei Tech
LG
Samsung
Ericsson

Borqs
AKMSemicond.
ARM
Atheros Comm
...
EMP
Samsung

SonyEricsson
Toshiba
8
Chapter1 5
SeeAndroidDevelopers
Shortvideo(4min.)
Sh i D B t
http://www.youtube.com/watch?v=7Y4thikvOM
ShowingDaveBort
andDanBorstein,
twomembersofthe
AndroidOpenSource
Projecttalkabout
theproject.
9
TheAndroidPlatform
Again,whatdidtheysayaboutAndroid?
Androidisasoftware environmentbuiltformobile
devices.
Itisnot ahardwareplatform.
Androidincludes:
LinuxkernelbasedOS,
arichUI,
telephonefunctionality,
enduserapplications,
code libraries, codelibraries,
applicationframeworks,
multimediasupport,...
UserapplicationsarebuiltforAndroidinJava.
10
Chapter1 6
AndroidsContext:MobileMarketPlayer$
Stakeholders:
Mobilenetwork operators want
Operators
Software Device
tolockdowntheirnetworks,
controllingandmeteringtraffic.
Device manufacturers wantto
differentiatethemselveswith
features,reliability,andprice
points.
Vendors Manufacturers
11
Software vendors wantcomplete
accesstothehardwaretodeliver
cuttingedgeapplications.
TheMaturingMobileExperience
Notsolongago Today
Electronictoolsofatypicalbusinesswarrior
1. Phone
2. Pager
3. PDAOrganizer
4. Laptop
5 Portable music player
1. Smartphone
2. Laptop(perhaps!)
5. Portablemusicplayer
6. NoInternet access/
limitedaccess
12
Tomorrow?
Chapter1 7
TheMaturingMobileExperience
Iwant my2015Smartphonetoactas
Trying to answer Tomorrow ?
1. Phone
2. Pager
3. PDAOrganizer
4. HighQualityCamera(still&video)
5. Portablemusicplayer
6. Portable TV/VideoPlayer/Radio
7. Laptop
8. PlayStation
9. GPS
10 G lf C dd (b ll i )
Tryingtoanswer:Tomorrow?
10. GolfCaddy(ballretrievertoo)
11. BookReader(Idontread,Itreadstome)
12. Car/Home/OfficeKey
13. RemoteControl(Garage,TV,)
14. CreditCard/DriversLicense/Passport
15. CashonDemand
16. Cook,housechores
17. Psychologist/Mentor/Adviser
18. ????
13
Androidvs.Competitors
1. AppleInc.
2. Microsoft
3. Nokia
4. Palm
5 Research In Motion
14
5. ResearchInMotion
6. Symbian
Chapter1 8
TheSizeof
theMobile
Market
http://gizmodo.com/5489036
/ ll h h /cellphoneovershare
[seeappendix]
15 15
AndroidComponents(Stack)
TheAndroidstackincludesalargearrayof
f t f bil li ti featuresformobileapplications.
ItwouldbeeasytoconfuseAndroidwitha
generalpurposecomputingenvironment.
Allofthemajorcomponentsofacomputing
platform are included platformareincluded.
16
Chapter1 9
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 10
AndroidComponents
Video1/3:AndroidsArchitecture
PresentedbyMikeCleron,GoogleCorp.(13min)
19
Availableat:http://www.youtube.com/watch?v=QBGfUs9mQYY
AndroidComponents
Video2/3:ApplicationsLifeCycle
PresentedbyMikeCleron,GoogleCorp.(8min)
20
Availableat:http://www.youtube.com/watch?v=fL6gSd4ugSI&feature=channel
Chapter1 11
AndroidComponents
Video3/3:AndroidsAPI
PresentedbyMikeCleron,GoogleCorp.(7min)
21
Availableat:http://www.youtube.com/watch?v=MPukbH6DlY&feature=channel
AndroidApplicationFramework
Video:
Inside the Insidethe
AndroidApplicationFramework
(about52min)
PresentedbyDanMorrill Google
AtGoogleDeveloperConference
SanFrancisco 2008
Availableat:
htt // it l / it /i /i id th d id li ti f k http://sites.google.com/site/io/insidetheandroidapplicationframework
22
Androidisdesignedtobefast,powerful,andeasytodevelopfor.Thissession
willdiscusstheAndroidapplicationframeworkindepth,showingyouthe
machinerybehindtheapplicationframework.
explainsthelifecycleofanandroidapk.verygood!
Chapter1 12
AndroidComponents
Video:
An Introduction to Android AnIntroductiontoAndroid
(about52min)
PresentedbyJasonChen Google
AtGoogleDeveloperConference
SanFrancisco 2008
Availableat:
http://wwwyoutube com/watch?v x1ZZ R3p w8 http://www.youtube.com/watch?v=x1ZZR3p_w8
23
WhyuseLinuxforaphone?
Linuxkernelisaproven coreplatform.
Reliability is more important than performance when it Reliability 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 13
Dalvik VirtualMachine
User applications ll core Android applications Userapplications,aswellascoreAndroidapplications,are
writteninJavaprogramminglanguageandarecompiledinto
bytecodes.
Androidbytecodesareinterpretedatruntimebyaprocessor
knownastheDalvik virtualmachine.
25
WhyanotherJavaVirtual Machine?
Androidbytecode filesarelogicallyequivalent
t J b t d b t th it A d id t toJavabytecodes,buttheypermitAndroidto
runitsapplicationsinitsownvirtualenvironmentthatis
freefromSunslicensingrestrictionsand
anopenplatformuponwhichGoogle,andpotentiallythe
opensourcecommunity,canimproveasnecessary.
26
Chapter1 14
Dalvik VirtualMachine
Video(61min)
D l ik VM I t l Dalvik VMInternals
PresentedbyDanBorstein
AtGoogleDeveloper 2008
Sanfrancisco
Availableat:
http://www.youtube.com/watch?v=ptjedOZEXPM
27
InsideAndroid:Intents
AnimportantandrecurringthemeofAndroid
development is the Intent developmentistheIntent.
AnIntentinAndroiddescribeswhatyouwanttodo.
Thismaylooklike
Iwanttolookupacontactrecord,or
Pleaselaunchthiswebsite,or
Sh h O d C fi i S ShowtheOrderConfirmationScreen.
Intentsareimportantbecausetheyfacilitate
navigationandrepresentthemostimportantaspect
ofAndroidcoding.
28
Chapter1 15
Intents&IntentFilters
AnIntent isadeclarationofneed.
AnIntent ismadeupofvariouspiecesincluding:
desiredaction orservice,
data,and
category ofcomponentthatshouldhandletheintentand
instructionsonhowtolaunchatargetactivity.
A I t tFilt i t i d l ti f bilit d AnIntentFilter isatrigger,adeclarationofcapabilityand
interestinofferingassistancetothoseinneed.
AnIntentFilter maybegenericorspecificwithrespectto
whichIntentsitofferstoservice.
29
Intents&IntentFilters
Anintent isanabstractdescriptionofanoperationtobe
performed. performed.
Itsmostsignificantuseisinthelaunchingofactivities,where
itcanbethoughtofasthegluebetweenactivities.
Theprimarypiecesofinformationinanintentare:
Action Data
Thegeneralactiontobe Thedatatooperateon,suchas
30
performed,suchas:
ACTION_VIEW,
ACTION_EDIT,
ACTION_MAIN,etc.
apersonrecordinthecontacts
database,expressedasaUri.
Chapter1 16
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
31
filledin.
ACTION_EDIT content://contacts/1 Editinformationabouttheperson
whoseidentifieris"1".
ACTION_VIEW content://contacts/ Displayalistofpeople,whichthe
usercanbrowsethrough.
DissectingIntents
1. Componentname Thenameofthecomponentthatshouldhandletheintent(for
example"com.example.project.app.MyActivity1").
2. Action Astringnamingtheactiontobeperformed or,inthecaseofbroadcast
intents,theactionthattookplaceandisbeingreported(forexample:ACTION_VIEW,
ACTION_CALL,ACTION_TIMEZONE_CHANGED,).
3. Data TheURIofthedatatobeactedonandtheMIMEtypeofthatdata(forexample
tel:/216 555-1234 , "http://maps.google.com,...).
4. Category Astringcontainingadditionalinformationaboutthekindofcomponentthat g y g g p
shouldhandletheintent(forexampleCATEGORY_BROWSABLE,
CATEGORY_LAUNCHER, ).
5. Extras Keyvaluepairs foradditionalinformationthatshouldbedeliveredtothe
componenthandlingtheintent.
6. Flags ofvarioussorts.
32
Chapter1 17
DeliveringIntents
AnIntentobjectispassedto
Context startActivity() or Activity startActivityForResult() Context.startActivity() orActivity.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 18
ExampleofIntent(1)
FollowingfragmentscallsanIntent whosejobisto
invoke a builtin task (ACTION VIEW) and explore the invokeabuilt intask(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 19
ExampleofIntent(1)
CompletecodetoseeContacts.
packagematos.cis493;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.net.Uri;
importandroid.os.Bundle;
publicclassAndDemo1extendsActivity{
/**showcontactlist*/
@Override
public void onCreate(Bundle savedInstanceState) {
37
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentmyIntent =newIntent( Intent.ACTION_VIEW,Uri.parse( "content://contacts/people"));
startActivity(myIntent);
}
}
ExampleofIntent(2)
FollowingIntent usesbuiltintask(ACTION_VIEW)to
explore a web page exploreawebpage
(seenewUrivalue)
Intent myIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(myIntent);
38
Chapter1 20
ExampleofIntent(3)
FollowingIntent usesbuiltintask(ACTION_VIEW)to
make a phone call 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 21
IntentFilters
WhenanIntent isdispatched,thesystemevaluates
theavailableActivities,Services,andregistered
BroadcastReceivers androutestheIntenttothemost
appropriate recipient(seenextFigure).
41
IntentFilters
42
Chapter1 22
IntentFilters
Toinformthesystemwhichimplicit intentstheycan y p y
handle,activities,services,andbroadcastreceivers can
haveoneormoreintentfilters.
Eachfilterdescribesacapabilitythatthecomponentis
willingtoreceive.
43
Anexplicit intentisalwaysdeliveredtoitstarget,nomatter
whatitcontains;thefilterisnotconsulted.
Butanimplicitintentisdeliveredtoacomponentonlyifit
canpassthroughoneofthecomponent'sfilters.
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".../>
<data android type "audio/mpeg" android scheme "http" />
44
<dataandroid:type="audio/mpeg"android:scheme="http".../>
...
</intentfilter>
Chapter1 23
AndroidApplications
EachAndroid applicationrunsinitsownLinux
process.
Anapplicationconsistsofacombinationofsoftware
componentsincluding:
Activities
Services
BroadcastReceivers
ContentProviders
45
AndroidApplications
Structureof
t i l atypical
Android
Application
46
Chapter1 24
AndroidServices
AService isanapplicationcomponentthatruns
in the background not interacting with the user inthebackground,notinteractingwiththeuser,
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
th i th d f th i h ti themainthreadoftheirhostingprocess.
Thismeansthat,ifyourserviceisgoingtodo
anyCPUintensive(suchasMP3playback)or
blocking (such as networking RSS exchange) blocking(suchasnetworking,RSSexchange)
operations,itshouldspawnitsownthreadin
whichtodothatwork
48
Chapter1 25
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;
d d importandroid.app.Activity;
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 26
AndroidServices
Service1DemoManifest
<?xmlversion="1.0"encoding="utf8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifestxmlns: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> </intent filter>
</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
07 01 02:50:25 857: INFO/service1(767): service1 firing : # 4 070102:50:25.857:INFO/service1(767):service1firing:#4
52
Chapter1 27
AndroidBroadcastReceiver
WhatisaBROADCASTRECEIVER?
If an application wants to receive and respond to a global event such as the Ifanapplicationwantstoreceiveandrespondtoaglobalevent,suchasthe
phoneringingoranincomingtextmessage,itmustregisterasaBroadcastReceiver.
AnapplicationregisterstoreceiveIntentsbyannouncinginthe
AndroidManfest.xmlfileitsIntentFilters.
IfthereceiverisregisteredintheAndroidManifest.xmlfile,itdoesnothaveto
berunninginordertobetriggered.
When the global event occurs the application is started automatically upon Whentheglobaleventoccurs,theapplicationisstartedautomaticallyupon
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 28
AndroidBroadcastReceiver
BROADCASTRECEIVER
BroadcastReceiver
sendBroadcast()
SomeActivity
onReceive()
onReceive()
BroadcastReceiver
55
onReceive()
BroadcastReceiver
AndroidBroadcastReceiver
Intentsvs.Broadcasts
StartinganActivitywithanIntentisaforeground
operationthatmodifieswhattheuseriscurrently
interactingwith.
BroadcastinganIntentisabackground operation
thattheuserisnotnormallyawareof.
56
Chapter1 29
AndroidBroadcastReceiver
TypeofBroadcasts
Therearetwomajorclassesofbroadcaststhatcanbereceived:
Normalbroadcasts (sentwithsendBroadcast)arecompletely
asynchronous.Allreceiversofthebroadcastareruninanundefined
order,oftenatthesametime.Thisismoreefficient,butmeansthat
receiverscannotusetheresultorabortAPIsincludedhere.
Orderedbroadcasts (sentwithsendOrderedBroadcast)are
delivered to one receiver at a time As each receiver executes in 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 30
AndroidBroadcastReceiver
BroadcastReceiverExample(1/5).InterceptarrivingSMS
package matos b oadcast ecei e package matos.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import 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 31
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 "Found our SMS Event!"); 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 32
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>
/ i i
63
</activity>
</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>
AndroidContentProvider
Contentproviders store andretrieve dataandmakeit
accessible to all applications. accessibletoallapplications.
TheyaretheonlywaytosharedataacrossAndroid
applications.There'snocommonstorageareathatallAndroid
packagescanaccess.
Androidshipswithanumberofcontentprovidersfor
commondatatypes(audio,video,images,personalcontact
information,andsoon).
64
Chapter1 33
AndroidContentProvider
ContentProviders areadatalayerprovidingdataabstraction
foritsclientsandcentralizingstorageandretrievalroutinesin
asingleplace.
AContentProvider mayprovidedatatoanActivityorService
inthesameapplicationsspaceaswellasanActivityor
Servicecontainedinotherapplications.
AContentProvider mayuseanyformofdatastorage
mechanismavailableontheAndroidplatform,includingfiles,
SQLite databases,orevenamemorybasedhashmapifdata
persistenceisnotrequired.
65
AndroidContentProvider
66
Chapter1 34
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
TheContentResolver methodtakesanURIasitsfirstargument.It'swhatidentifies
whichprovidertheContentResolver shouldtalktoandwhichtableoftheprovider
isbeingtargeted.
68
Chapter1 35
AndroidContentProvider
QueryingaContentProvider
You need three pieces of information to query a content Youneedthreepiecesofinformationtoqueryacontent
provider:
TheURIthatidentifiestheprovider
Thenamesofthedatafieldsyouwanttoreceive
Thedatatypesforthosefields
Ifyou'requeryingaparticularrecord,youalsoneedtheIDfor
that record thatrecord.
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 36
AndroidContentProvider
Example:PostingaquerytotheContactlist(2/2)
<?xml version="1.0" encoding="utf-8"?>
<manifest mlns android "http //schemas android com/apk/res/android" <manifest xmlns: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.xml file AndroidManifest.xmlfile
(withpreciselythatname)initsroot
directory.
Themanifestpresentsessential
informationabouttheapplicationto
the Android system information the theAndroidsystem,informationthe
systemmusthavebeforeitcanrunany
oftheapplication'scode.
72
Chapter1 37
AndroidManifestxmlFile
Thesearetheonlylegalelements;youcannotaddyourownelementsorattributes.
<action>
<activity>
<activityalias>
<application>
<category>
<data>
<grant uri permission>
<permission>
<permissiongroup>
<permissiontree>
<provider>
<receiver>
<service>
<uses configuration> <granturipermission>
<instrumentation>
<intentfilter>
<manifest>
<metadata>
<usesconfiguration>
<useslibrary>
<usespermission>
<usessdk>
73
AndroidManifestxmlFile
Amongotherthings,themanifestdoesthefollowing:
ItnamestheJavapackagefortheapplication.Thepackagenameservesasauniqueidentifier
for the application fortheapplication.
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 38
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 39
Example.Currencyconverter
77
Example.Currencyconverter
package matos.currencyconvereter;
import android.app.Activity;
i d id dl import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import 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;
78
// GUI widgets
Button btnConvert;
Button btnClear;
EditText txtUSDollars;
EditText txtEuros;
EditText txtColones;
Chapter1 40
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() {
79
btnClear.setOnClickListener(new OnClickListener() {
// clear the text boxes
@Override
public void onClick(View v) {
txtColones.setText("");
txtEuros.setText("");
txtUSDollars.setText("");
}
});
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() "Invalid data try again"
80
Toast.makeText(v.getContext(), "Invalid data - try again" ,
Toast.LENGTH_SHORT).show();
}
}
});// setOnClick...
}// onCreate
}// class
Chapter1 41
Example.Currencyconverter
81
Example.Currencyconverter
Resource:res/layout/main.xml(1/2)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
<AbsoluteLayout
d id id "@+id/ b L t"
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"
android:id="@+id/absLayout"
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>
82
>
</TextView>
<TextView
android:id="@+id/greenFiller1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff006666"
>
</TextView>
<EditText
android:id="@+id/txtUSDollars"
android:layout_width="150px"
android:layout_height="wrap_content"
android:layout_x="130px"
android:layout_y="10px"
>
</TextView>
Chapter1 42
Example.Currencyconverter
Resource:res/layout/main.xml(2/2)
<EditText
android:id="@+id/txtEuros"
<Button
d id id "@+id/bt C t"
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"
>
android:id="@+id/btnConvert"
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"
d id l t "190 "
83
</TextView>
<EditText
android:id="@+id/txtColones"
android:layout_width="150px"
android:layout_height="wrap_content
android:layout_x="130px"
android:layout_y="130px"
>
</EditText>
android:layout_y="190px"
>
</Button>
</AbsoluteLayout>
</LinearLayout>
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
d id " d id i t t t LAUNCHER" />
84
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
Chapter1 43
AdditionalResources
GoogleDeveloperConference
SanFrancisco 2009
Webpage:http://code.google.com/events/io/
85

You might also like