Chapter1‐ 1
Chapter1
AndroidDevelopment
Introduction
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
Ad idDl
A
n
d
ro
id
D
eve
l
opers
/>&
UnlockingAndroid
byFrankAbleson,CharlieCollins,andRobi Sen.
ISBN978‐1‐933988‐67‐2
ManningPublications,2009.
1
Chapter1‐ Goals
THEBIGPICTURE
1. WhatisAndroid?
2. Overviewdevelopmentenvironment
2
Chapter1‐ 2
Chapter1‐ Resources
Android’swebpage
/>3
WhatisAndroid?
• Android isanopen‐sourcesoftwareplatform
tdb Gl
d th
O Hdt
crea
t
e
d
b
y
G
oog
l
ean
d
th
e
O
pen
H
an
d
se
t
Alliance.
• Itisprimarilyusedtopowermobilephones.
• Ithasthecapabilitytomakeinroadsinmany
other(non‐phone)embeddedapplication
markets.
4
Chapter1‐ 3
WhatisAndroid?
• Android™consistsofacompletesetof
ft t f bil di
so
ft
warecomponen
t
s
f
ormo
bil
e
d
ev
i
ces
including:
– anoperatingsystem,
– middleware,and
embedded key mobile applications
–
embedded
key
mobile
applications
– alargemarket.
5
WhyAndroid?
Listenfromtheprojectcreators/developers (2.19min)
– NickSears.Co‐founderofAndroid
St HitEi i Di t
–
St
eve
H
orow
it
z.
E
ng
i
neer
i
ng
Di
rec
t
or
– DamMorrill.Developer
– Peisun Wu.EngineeringProjectManager
– ErickTseng.ProjectManager
– Iliyan Malchev.Engineer
– MikeCleron.SoftwareManager
– PerGustafsson.Gr aphicsDesigner.
– etc…
• />d
e
d
• Youwillhearstatementssuchas
“…currentlyitistoodifficulttomakenewproducts…opensoftwarebringsmore
innovation…choices…lowercosts…moreapplicationssuchasfamilyplanner,my
taxes,understandmywifebetter,…”
6
Chapter1‐ 4
WhatisOpenHandsetAlliance?
• Quotingfr omwww.OpenHandsetAlliance.com
page
• “…OpenHandsetAlliance™,agroupof47technology
andmobilecompanieshavecometogethertoaccelerate
innovationinmobileandofferconsumersaricher,less
expensive,andbettermobileexperience.
• TogetherwehavedevelopedAndroid™,thefirst
complete open and free mobile
platform
complete
,
open
,
and
free
mobile
platform
.
• Wearecommittedtocommerciallydeployhandsetsand
servicesusingtheAndroidPlatform.“
7
OpenHandsetAllianceMembers
Operators
SoftwareCo.
Commercializat. Semiconductor HandsetManf
ChinaMobile AscenderCorp. Aplix Audience ACER
ChinaUnicom
KDDICorp.
NTTDoCoMo
SprintNextel
T‐Mobile
TelecomItalia
Telefóni ca
Vodafone
Softbank
eBay
Esmertec
Google
LivingImage
NMSComm.
NuanceComm.
PacketVideo
SkyPop
SONiVOX
Noser Engineering
AstonishingTribe
WindRiverSystems
OmronSoftware
…
Teleca
BroadcomCorp.
IntelCorp.
MarvellTec h.
Group
Nvidia Corp.
Qualcomm
SiRF Tech.Holdings
Synaptics
Texas Instr.
AKM
Semicond
ASUS
HTC
LG
Motorola
Samsung
ASUSTek
Garmin
Huawei Tech
LG
Samsung
…
Ericsson
…
Borqs
AKM
Semicond
.
ARM
Atheros Comm
EMP
Samsung
…
SonyEricsson
Toshiba
8
Chapter1‐ 5
SeeAndroidDevelopers
Shortvideo(4min.)
Sh i
D
Bt
/>Sh
ow
i
ng
D
ave
B
or
t
andDanBorstein,
twomembersofthe
AndroidOpenSource
Projecttalkabout
theproject
.
9
TheAndroidPlatform
Again,whatdidtheysayaboutAndroid?
• Androidisasoftware environmentbuiltformobile
devices.
• Itisnot ahardwareplatform.
• Androidincludes:
• Linuxkernel‐basedOS,
• arichUI,
• telephonefunctionality,
• end‐userapplications,
•
code
libraries,
code
libraries,
• applicationframeworks,
• multimediasupport,
• UserapplicationsarebuiltforAndroidinJava.
10
Chapter1‐ 6
Android’sContext:MobileMarketPlayer$
Stakeholders:
Mobilenetwork operators want
Operators
SoftwareDevice
tolockdowntheirnetworks,
contr ollingandmeteringtraffic.
Device manufacturers wantto
differentiatethemselveswith
features,reliability,andprice
points.
VendorsManufacturers
11
Software vendors wantcomplete
accesstothehardwaretodeliver
cutting‐edgeapplications.
TheMaturingMobileExperience
Notsolongago…Today
Electronictoolsofatypicalbusinesswarrior
1. Phone
2. Pager
3. PDAOrganizer
4. Laptop
5
Portable music player
1. Smartphone
2. Laptop(perhaps!)
5
.
Portable
music
player
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. Po rtablemusicplayer
6. Po rtable TV/VideoPlayer/Radio
7. Laptop
8. PlayStation
9. GPS
10
GlfCdd (b ll i )
Trying
to
answer
:
Tomorrow
?
10
.
G
o
lf
C
a
dd
y
(b
a
ll
retr
i
evertoo
)
11. BookReader(Idon’tread,Itreadstome)
12. Car/Home/OfficeKey
13. RemoteControl(Garage,TV,…)
14. CreditCard/Driver ’sLicense/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
.
Research
In
Motion
6.Symbian
Chapter1‐ 8
TheSizeof
theMobile
Market
/>/llh
h
/
ce
ll
p
h
one‐overs
h
are
[seeappendix]
1515
AndroidComponents(Stack)
• TheAndroidstackincludesalargearrayof
ft f bil li ti
f
ea
t
ures
f
ormo
bil
eapp
li
ca
ti
ons.
• ItwouldbeeasytoconfuseAndroidwitha
generalpurposecomputingenvironment.
• Allofthemajorcomponentsofacomputing
platform are included
platform
are
included
.
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)
• GSMTele
p
hon
y
(
hardwarede
p
endent
)
py
( p)
• Bluetooth,EDGE,3G,4G,andWi‐Fi (hardwaredependent)
• Camera,GPS,compass,andaccelerometer (hardwaredependent)
• Richdevelopmentenvironment includingadeviceemulator,toolsfor
debugging,memoryandperformanceprofiling,andaplugin forthe
EclipseIDE
17
AndroidComponents
18
Chapter1‐ 10
AndroidComponents
Video1/3:Android’sArchitecture
PresentedbyMikeCleron,GoogleCorp.(13min)
19
Availableat: />AndroidComponents
Video2/3:Application’sLifeCycle
PresentedbyMikeCleron,GoogleCorp.(8min)
20
Availableat: />Chapter1‐ 11
AndroidComponents
Video3/3:Android’sAPI
PresentedbyMikeCleron,GoogleCorp.(7min)
21
Availableat: />AndroidApplicationFramework
Video:
Inside the
Inside
the
AndroidApplicationFramework
(about52min)
PresentedbyDanMorrill– Google
AtGoogleDeveloperConference
SanFrancisco‐ 2008
Availableat:
htt //it l /it /i /i id
th
did
li ti
fk
htt
p:
//
s
it
es.goog
l
e.com
/
s
it
e
/i
o
/i
ns
id
e‐
th
e‐an
d
ro
id
‐app
li
ca
ti
on‐
f
ramewor
k
22
Androidisdesignedtobefast,powerful,andeasytodevelopfor.Thissession
willdiscusstheAndroidapplicationframeworkindepth,showingyouthe
machinerybehindtheapplicationframework.
explainsthelife‐cycleofanandroidapk.verygood!
Chapter1‐ 12
AndroidComponents
Video:
An Introduction to Android
An
Introduction
to
Android
(about52min)
PresentedbyJasonChen– Google
AtGoogleDeveloperConference
SanFrancisco‐ 2008
Availableat:
http://www youtube com/watch?v x1ZZ
R3p w8
http://www
.
youtube
.
com/watch?v
=
x1ZZ
‐
R3p
_
w8
23
WhyuseLinuxforaphone?
• Linuxkernelisaproven coreplatform.
•
Reliability
is more important than performance when it
•
Reliability
is
more
important
than
performance
when
it
comestoamobilephone,becausevoicecommunicationis
theprimaryuseofaphone.
• Linuxprovidesahardwareabstractionlayer,lettingtheupper
levelsremainunchangeddespitechangesintheunderlying
hardware.
•
As new
accessories
appear on the market
drivers
can be
•
As
new
accessories
appear
on
the
market
,
drivers
can
be
writtenattheLinuxleveltoprovidesupport,justasonother
Linuxplatforms.
24
Chapter1‐ 13
Dalvik VirtualMachine
User applications
ll
core Android applications
•
User
applications
,aswe
ll
as
core
Android
applications
,are
writteninJavaprogramminglanguageandarecompiledinto
bytecodes.
• Androidbytecodesareinterpretedatruntimebyaprocessor
knownastheDalvik virtualmachine.
25
WhyanotherJavaVirtual Machine?
• Androidbytecode filesarelogicallyequivalent
t J
bt d
btth it Ad idt
t
o
J
ava
b
y
t
eco
d
es,
b
u
t
th
eyperm
it
A
n
d
ro
id
t
o
– runitsapplicationsinitsownvirtualenvironmentthatis
freefromSun’slicensingrestrictionsand
– anopenplatformuponwhichGoogle,andpotentiallythe
opensourcecommunity,canimproveasnecessary.
26
Chapter1‐ 14
Dalvik VirtualMachine
Video(61min)
Dlik
VM It l
D
a
l
v
ik
VM
I
n
t
erna
l
s
PresentedbyDanBorstein
AtGoogleDeveloper– 2008
Sanfrancisco
Availableat:
/>27
InsideAndroid:Intents
• AnimportantandrecurringthemeofAndroid
development is the
Intent
development
is
the
Intent
.
• AnIntentinAndroiddescribeswhatyouwanttodo.
• Thismaylooklike
– “Iwanttolookupacontactrecord,”or
– “Pleaselaunchthiswebsite,”or
“
Sh h Od Cfi i S
”
–
“
Sh
owt
h
e
O
r
d
er
C
on
fi
rmat
i
on
S
creen.
”
• Intentsareimportantbecausetheyfacilitate
navigationandrepresentthemostimportantaspect
ofAndroidcoding.
28
Chapter1‐ 15
Intents&IntentFilters
• AnIntent isadeclarationofneed.
• AnIntent ismadeupofvariouspiecesincluding:
– desiredaction orservice,
– data,and
– category ofcomponentthatshouldhandletheintentand
instructionsonhowtolaunchatargetactivity.
A
I t tFilt
i ti dl ti f bilit d
•
A
n
I
n
t
en
tFilt
er
i
sa
t
r
i
gger,a
d
ec
l
ara
ti
ono
f
capa
bilit
yan
d
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,et c.
apersonrecordinthecontacts
database,expressedasaUri.
Chapter1‐ 16
Intents&IntentFilters
SomeexamplesofIntent’saction/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 , "”
, ).
4. Cate
g
or
y
Astrin
g
containin
g
additionalinformationaboutthekindofcom
p
onentthat
gy
g g p
shouldhandletheintent(forexampleCATEGORY_BROWSABLE,
CATEGORY_LAUNCHER, …
).
5. Extras Key‐valuepairs foradditionalinformationthatshouldbedeliveredtothe
componenthandlingtheintent.
6. Flags ofvarioussorts.
32
Chapter1‐ 17
DeliveringIntents
• AnIntentobjectispassedto
Context startActivity
()
or
Activity startActivityForResult
()
Context
.
startActivity
()
or
Activity
.
startActivityForResult
()
tolaunchanactivityorgetanexistingactivitytodosomething
new(asynchronous &synchronouslyrespectively).
• AnIntentobjectispassedtoContext.startService() toinitiatea
serviceordelivernewinstructionstoanongoingservice.
• AnintentcanbepassedtoContext.bindService() to establisha
connectionbetweenthecallingcomponentandatarget
service.Itcanoptionallyinitiatetheserviceifit'snotalready
running.
33
IntentResolution
Intentscanbedividedintotwogroups:
•
Explicit intents
designate the target component by its name
•
Explicit
intents
designate
the
target
component
by
its
name
,
typicallyusedforanactivitystartingasubordinateserviceor
launchingasisteractivity.
• Implicitintents donotnameatarget(thefieldforthe
componentnameisblank).Implicitintentsareoftenusedto
activatecomponentsinotherapplications.Latebinding
applies
applies
.
WheneverpossibleAndroiddeliversanexplicitintenttoan
instanceofthedesignatedtargetclass.
34
Chapter1‐ 18
ExampleofIntent(1)
• FollowingfragmentscallsanIntent whosejobisto
invoke a built
‐
in task (
ACTION VIEW
) and explore the
invoke
a
built
in
task
(
ACTION
_
VIEW
)
and
explore
the
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
public
void
onCreate
(Bundle
savedInstanceState
)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentmyIntent =newIntent( Intent.ACTION_VIEW,Uri.parse( "content://contacts/people"));
startActivity(myIntent);
}
}
ExampleofIntent(2)
• FollowingIntent usesbuilt‐intask(ACTION_VIEW)to
explore a web page
explore
a
web
page
(seenewUrivalue)
Intent myIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(""));
startActivity(myIntent);
38
Chapter1‐ 20
ExampleofIntent(3)
• FollowingIntent usesbuilt‐intask(ACTION_VIEW)to
make a phone call
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‐ 21
IntentFilters
• WhenanIntent isdispatched,thesystemevaluates
theavailableActivities,Services,andregistered
BroadcastReceivers androutestheIntenttothemost
appropriate recipient(seenextFigure).
41
IntentFilters
42
Chapter1‐ 22
IntentFilters
• Toinformthes
y
stemwhichim
p
licit intentsthe
y
can
y
p
y
handle,activities,services,andbroadcastreceivers can
haveoneormoreintentfilters.
• Eachfilterdescribesacapabilitythatthecomponentis
willingtoreceive.
43
• Anexplicit intentisalwaysdeliveredtoitstarget,nomatter
whatitcontains;thefilterisnotconsulted.
• Butanimplicitintentisdeliveredtoacomponentonlyifit
canpassthroughoneofthecomponent'sfilters.
IntentFilters
• IntentFilters a reoftendefinedinana
pp
lication’s
pp
AndroidManifest.xmlwiththe<intent‐filter> tag.
<intent‐filter...>
<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
<data
android
:
type
=
"audio/mpeg"
android
:
scheme
=
"http"
...
/>
...
</intent‐filter>
Chapter1‐ 23
AndroidApplications
• EachAndroid applicationrunsinitsownLinux
process.
• Anapplicationconsistsofacombinationofsoftware
componentsincluding:
– Activities
– Services
–
BroadcastReceivers
– ContentProviders
45
AndroidApplications
Structureof
til
a
t
yp
i
ca
l
Android
Application
46
Chapter1‐ 24
AndroidServices
• AService isanapplicationcomponentthatruns
in the background not interacting with the user
in
the
background
,
not
interacting
with
the
user
,
foranindefiniteperiodoftime.
• Eachserviceclassmusthav e acorresponding
<service> declarationinitspackage's
AndroidManifest.xml.
•
Services can be started/stopped with
Services
can
be
started/stopped
with
– Context.startService()and
– Context.bindService().
– stopService(…)andunbindService(…)
47
AndroidServices
• Services,likeotherapplicationobjects,runin
th i th d f th i hti
th
ema
i
n
th
rea
d
o
f
th
e
i
r
h
os
ti
ngprocess.
• Thismeansthat,ifyourserviceisgoingtodo
anyCPUintensive(suchasMP3playback)or
blocking (such as networking RSS exchange)
blocking
(such
as
networking
,
RSS
exchange)
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) {
t
r
y
{
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;
dd
importan
d
roi
d
.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