Tải bản đầy đủ (.pdf) (43 trang)

Android chapter01 intro handout

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.9 MB, 43 trang )

Chapter1‐ 1
Chapter1
AndroidDevelopment
Introduction
VictorMatos
ClevelandStateUniversity
Notesarebasedon:
Ad idDl
A
n
d
ro
id

D
eve
l
opers
/>&
UnlockingAndroid
byFrankAbleson,CharlieCollins,andRobi Sen.
ISBN978‐1‐933988‐67‐2
ManningPublications,2009.
1
Chapter1‐ Goals
THEBIGPICTURE
1. WhatisAndroid?
2. Overviewdevelopmentenvironment
2
Chapter1‐ 2
Chapter1‐ Resources


Android’swebpage
/>3
WhatisAndroid?
• Android isanopen‐sourcesoftwareplatform
tdb Gl
d th
O Hdt
crea
t
e
d

b
y
G
oog
l
ean
d

th
e
O
pen
H
an
d
se
t


Alliance.
• Itisprimarilyusedtopowermobilephones.
• Ithasthecapabilitytomakeinroadsinmany
other(non‐phone)embeddedapplication
markets.
4
Chapter1‐ 3
WhatisAndroid?
• Android™consistsofacompletesetof
ft t f bil di
so
ft
warecomponen
t
s
f
ormo
bil
e
d
ev
i
ces
including:
– anoperatingsystem,
– middleware,and
embedded key mobile applications

embedded


key

mobile

applications
– alargemarket.
5
WhyAndroid?
Listenfromtheprojectcreators/developers (2.19min)
– NickSears.Co‐founderofAndroid
St HitEi i Di t

St
eve
H
orow
it
z.
E
ng
i
neer
i
ng
Di
rec
t
or
– DamMorrill.Developer
– Peisun Wu.EngineeringProjectManager

– ErickTseng.ProjectManager
– Iliyan Malchev.Engineer
– MikeCleron.SoftwareManager
– PerGustafsson.Gr aphicsDesigner.
– etc…
• />d
e
d
• Youwillhearstatementssuchas
“…currentlyitistoodifficulttomakenewproducts…opensoftwarebringsmore
innovation…choices…lowercosts…moreapplicationssuchasfamilyplanner,my
taxes,understandmywifebetter,…”
6
Chapter1‐ 4
WhatisOpenHandsetAlliance?
• Quotingfr omwww.OpenHandsetAlliance.com
page
• “…OpenHandsetAlliance™,agroupof47technology
andmobilecompanieshavecometogethertoaccelerate
innovationinmobileandofferconsumersaricher,less
expensive,andbettermobileexperience.
• TogetherwehavedevelopedAndroid™,thefirst
complete open and free mobile
platform
complete
,
open
,
and


free

mobile

platform
.
• Wearecommittedtocommerciallydeployhandsetsand
servicesusingtheAndroidPlatform.“
7
OpenHandsetAllianceMembers
Operators
SoftwareCo.
Commercializat. Semiconductor HandsetManf
ChinaMobile AscenderCorp. Aplix Audience ACER
ChinaUnicom
KDDICorp.
NTTDoCoMo
SprintNextel
T‐Mobile
TelecomItalia
Telefóni ca
Vodafone
Softbank
eBay
Esmertec
Google
LivingImage
NMSComm.
NuanceComm.
PacketVideo

SkyPop
SONiVOX
Noser Engineering
AstonishingTribe
WindRiverSystems
OmronSoftware

Teleca
BroadcomCorp.
IntelCorp.
MarvellTec 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

SonyEricsson
Toshiba
8
Chapter1‐ 5
SeeAndroidDevelopers
Shortvideo(4min.)
Sh i
D
Bt
/>Sh
ow
i
ng
D
ave
B
or

t
andDanBorstein,
twomembersofthe
AndroidOpenSource
Projecttalkabout
theproject
.
9
TheAndroidPlatform
Again,whatdidtheysayaboutAndroid?
• Androidisasoftware environmentbuiltformobile
devices.
• Itisnot ahardwareplatform.
• Androidincludes:
• Linuxkernel‐basedOS,
• arichUI,
• telephonefunctionality,
• end‐userapplications,

code
libraries,
code

libraries,

• applicationframeworks,
• multimediasupport,
• UserapplicationsarebuiltforAndroidinJava.
10
Chapter1‐ 6

Android’sContext:MobileMarketPlayer$
Stakeholders:
Mobilenetwork operators want
Operators
SoftwareDevice
tolockdowntheirnetworks,
contr ollingandmeteringtraffic.
Device manufacturers wantto
differentiatethemselveswith
features,reliability,andprice
points.
VendorsManufacturers
11
Software vendors wantcomplete
accesstothehardwaretodeliver
cutting‐edgeapplications.
TheMaturingMobileExperience
Notsolongago…Today
Electronictoolsofatypicalbusinesswarrior
1. Phone
2. Pager
3. PDAOrganizer
4. Laptop
5
Portable music player
1. Smartphone
2. Laptop(perhaps!)
5
.
Portable


music

player
6. NoInternet access/
limitedaccess
12
Tomorrow?
Chapter1‐ 7
TheMaturingMobileExperience
Iwant my2015Smartphonetoactas…
Trying to answer Tomorrow ?
1. Phone
2. Pager
3. PDAOrganizer
4. HighQualityCamera(still&video)
5. Po rtablemusicplayer
6. Po rtable TV/VideoPlayer/Radio
7. Laptop
8. PlayStation
9. GPS
10
GlfCdd (b ll i )
Trying

to

answer
:
Tomorrow


?
10
.
G
o
lf

C
a
dd
y
(b
a
ll
retr
i
evertoo
)
11. BookReader(Idon’tread,Itreadstome)
12. Car/Home/OfficeKey
13. RemoteControl(Garage,TV,…)
14. CreditCard/Driver ’sLicense/Passport
15. CashonDemand
16. Cook,housechores
17. Psychologist/Mentor/Adviser
18. ????
13
Androidvs.Competitors
1.AppleInc.

2.Microsoft
3.Nokia
4.Palm
5
Research In Motion
14
5
.
Research

In

Motion
6.Symbian
Chapter1‐ 8
TheSizeof
theMobile
Market
/>/llh
h
/
ce
ll
p
h
one‐overs
h
are
[seeappendix]
1515

AndroidComponents(Stack)
• TheAndroidstackincludesalargearrayof
ft f bil li ti
f
ea
t
ures
f
ormo
bil
eapp
li
ca
ti
ons.
• ItwouldbeeasytoconfuseAndroidwitha
generalpurposecomputingenvironment.
• Allofthemajorcomponentsofacomputing
platform are included
platform

are

included
.
16
Chapter1‐ 9
AndroidComponents
• Applicationframework enablingreuseandreplacementofcomponents
• Dalvik virtualmachine optimizedformobiledevices

• Integratedbrowser basedontheopensourceWebKit engine
• Optimizedgraphics poweredbyacustom2Dgraphicslibrary;3Dgraphics
basedontheOpenGLESspecification(hardwareaccelerationoptional)
• SQLite forstructureddatastorage
• Mediasupport forcommonaudio,video,andstillimageformats(MPEG4,
H.264,MP3,AAC,AMR,JPG,PNG,
GIF)
• GSMTele
p
hon
y
(
hardwarede
p
endent
)

py
( p)
• Bluetooth,EDGE,3G,4G,andWi‐Fi (hardwaredependent)
• Camera,GPS,compass,andaccelerometer (hardwaredependent)
• Richdevelopmentenvironment includingadeviceemulator,toolsfor
debugging,memoryandperformanceprofiling,andaplugin forthe
EclipseIDE
17
AndroidComponents
18
Chapter1‐ 10
AndroidComponents
Video1/3:Android’sArchitecture

PresentedbyMikeCleron,GoogleCorp.(13min)
19
Availableat: />AndroidComponents
Video2/3:Application’sLifeCycle
PresentedbyMikeCleron,GoogleCorp.(8min)
20
Availableat: />Chapter1‐ 11
AndroidComponents
Video3/3:Android’sAPI
PresentedbyMikeCleron,GoogleCorp.(7min)
21
Availableat: />AndroidApplicationFramework
Video:
Inside the
Inside

the

AndroidApplicationFramework
(about52min)
PresentedbyDanMorrill– Google
AtGoogleDeveloperConference
SanFrancisco‐ 2008
Availableat:
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
Androidisdesignedtobefast,powerful,andeasytodevelopfor.Thissession
willdiscusstheAndroidapplicationframeworkindepth,showingyouthe
machinerybehindtheapplicationframework.
explainsthelife‐cycleofanandroidapk.verygood!
Chapter1‐ 12
AndroidComponents
Video:
An Introduction to Android
An

Introduction

to

Android

(about52min)
PresentedbyJasonChen– Google
AtGoogleDeveloperConference
SanFrancisco‐ 2008
Availableat:
http://www youtube com/watch?v x1ZZ
R3p w8
http://www
.
youtube
.
com/watch?v
=

x1ZZ

R3p
_
w8
23
WhyuseLinuxforaphone?
• Linuxkernelisaproven coreplatform.

Reliability
is more important than performance when it

Reliability
is

more

important

than

performance

when

it

comestoamobilephone,becausevoicecommunicationis
theprimaryuseofaphone.
• Linuxprovidesahardwareabstractionlayer,lettingtheupper

levelsremainunchangeddespitechangesintheunderlying
hardware.

As new
accessories
appear on the market
drivers
can be

As

new

accessories
appear

on

the

market
,
drivers
can

be

writtenattheLinuxleveltoprovidesupport,justasonother
Linuxplatforms.
24

Chapter1‐ 13
Dalvik VirtualMachine
User applications
ll
core Android applications

User

applications
,aswe
ll
as
core

Android

applications
,are
writteninJavaprogramminglanguageandarecompiledinto
bytecodes.
• Androidbytecodesareinterpretedatruntimebyaprocessor
knownastheDalvik virtualmachine.
25
WhyanotherJavaVirtual Machine?
• Androidbytecode filesarelogicallyequivalent
t J
bt d
btth it Ad idt
t
o

J
ava
b
y
t
eco
d
es,
b
u
t

th
eyperm
it

A
n
d
ro
id

t
o
– runitsapplicationsinitsownvirtualenvironmentthatis
freefromSun’slicensingrestrictionsand
– anopenplatformuponwhichGoogle,andpotentiallythe
opensourcecommunity,canimproveasnecessary.
26
Chapter1‐ 14

Dalvik VirtualMachine
Video(61min)
Dlik
VM It l
D
a
l
v
ik
VM

I
n
t
erna
l
s
PresentedbyDanBorstein
AtGoogleDeveloper– 2008
Sanfrancisco
Availableat:
/>27
InsideAndroid:Intents
• AnimportantandrecurringthemeofAndroid
development is the
Intent
development

is


the

Intent
.
• AnIntentinAndroiddescribeswhatyouwanttodo.
• Thismaylooklike
– “Iwanttolookupacontactrecord,”or
– “Pleaselaunchthiswebsite,”or

Sh h Od Cfi i S



Sh
owt
h
e
O
r
d
er
C
on
fi
rmat
i
on
S
creen.



• Intentsareimportantbecausetheyfacilitate
navigationandrepresentthemostimportantaspect
ofAndroidcoding.
28
Chapter1‐ 15
Intents&IntentFilters
• AnIntent isadeclarationofneed.
• AnIntent ismadeupofvariouspiecesincluding:
– desiredaction orservice,
– data,and
– category ofcomponentthatshouldhandletheintentand
instructionsonhowtolaunchatargetactivity.
A
I t tFilt
i ti dl ti f bilit d

A
n
I
n
t
en
tFilt
er
i
sa
t
r
i

gger,a
d
ec
l
ara
ti
ono
f
capa
bilit
yan
d

interestinofferingassistancetothoseinneed.
• AnIntentFilter maybegenericorspecificwithrespectto
whichIntentsitofferstoservice.
29
Intents&IntentFilters
• Anintent isanabstractdescriptionofanoperationtobe
performed.
performed.
• Itsmostsignificantuseisinthelaunchingofactivities,where
itcanbethoughtofasthegluebetweenactivities.
• Theprimarypiecesofinformationinanintentare:
Action Data
Thegeneralactiontobe Thedatatooperateon,suchas
30
performed,suchas:
ACTION_VIEW,
ACTION_EDIT,

ACTION_MAIN,et c.
apersonrecordinthecontacts
database,expressedasaUri.
Chapter1‐ 16
Intents&IntentFilters
SomeexamplesofIntent’saction/datapairsare:
ACTION_VIEW content://contacts/1 ‐‐ Displayinformationaboutthe
personwhoseidentifieris"1".
ACTION_DIAL content://contacts/1 ‐‐ Displaythephonedialerwiththe
personfilledin.
ACTION_VIEW tel:123 ‐‐ Displaythephonedialerwiththegivennumber
filledin
ACTION_DIAL tel:123 ‐‐ Displaythephonedialerwiththegivennumber
31
filledin.
ACTION_EDIT content://contacts/1 ‐‐ Editinformationabouttheperson
whoseidentifieris"1".
ACTION_VIEW content://contacts/ ‐‐ Displayalistofpeople,whichthe
usercanbrowsethrough.
DissectingIntents
1. Componentname Thenameofthecomponentthatshouldhandletheintent(for
example"com.example.project.app.MyActivity1").
2. Action Astringnamingtheactiontobeperformed—or,inthecaseofbroadcast
intents,theactionthattookplaceandisbeingreported(forexample:ACTION_VIEW,
ACTION_CALL,ACTION_TIMEZONE_CHANGED,…).
3. Data TheURIofthedatatobeactedonandtheMIMEtypeofthatdata(forexample
tel:/216 555-1234 , "”
, ).
4. Cate
g

or
y
Astrin
g
containin
g
additionalinformationaboutthekindofcom
p
onentthat
gy
g g p
shouldhandletheintent(forexampleCATEGORY_BROWSABLE,
CATEGORY_LAUNCHER, …
).
5. Extras Key‐valuepairs foradditionalinformationthatshouldbedeliveredtothe
componenthandlingtheintent.
6. Flags ofvarioussorts.
32
Chapter1‐ 17
DeliveringIntents
• AnIntentobjectispassedto
Context startActivity
()
or
Activity startActivityForResult
()
Context
.
startActivity
()

or

Activity
.
startActivityForResult
()
tolaunchanactivityorgetanexistingactivitytodosomething
new(asynchronous &synchronouslyrespectively).
• AnIntentobjectispassedtoContext.startService() toinitiatea
serviceordelivernewinstructionstoanongoingservice.
• AnintentcanbepassedtoContext.bindService() to establisha
connectionbetweenthecallingcomponentandatarget
service.Itcanoptionallyinitiatetheserviceifit'snotalready
running.
33
IntentResolution
Intentscanbedividedintotwogroups:

Explicit intents
designate the target component by its name

Explicit

intents
designate

the

target


component

by

its

name
,
typicallyusedforanactivitystartingasubordinateserviceor
launchingasisteractivity.
• Implicitintents donotnameatarget(thefieldforthe
componentnameisblank).Implicitintentsareoftenusedto
activatecomponentsinotherapplications.Latebinding
applies
applies
.
WheneverpossibleAndroiddeliversanexplicitintenttoan
instanceofthedesignatedtargetclass.
34
Chapter1‐ 18
ExampleofIntent(1)
• FollowingfragmentscallsanIntent whosejobisto
invoke a built

in task (
ACTION VIEW
) and explore the
invoke

a


built
in

task

(
ACTION
_
VIEW
)

and

explore

the

Contacts availableinthephone.
Intent myIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("content://contacts/people"));
startActivity(myIntent);
35
ExampleofIntent(1)
Intentuses
ACTION_VIEW
tosee
Contacts.
36

Chapter1‐ 19
ExampleofIntent(1)
• CompletecodetoseeContacts.
packagematos.cis493;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.net.Uri;
importandroid.os.Bundle;
publicclassAndDemo1extendsActivity{
/**showcontactlist*/
@Override
public void
onCreate
(Bundle
savedInstanceState
) {
37
public

void

onCreate
(Bundle

savedInstanceState
)

{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

IntentmyIntent =newIntent( Intent.ACTION_VIEW,Uri.parse( "content://contacts/people"));
startActivity(myIntent);
}
}
ExampleofIntent(2)
• FollowingIntent usesbuilt‐intask(ACTION_VIEW)to
explore a web page
explore

a

web

page

(seenewUrivalue)
Intent myIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(""));
startActivity(myIntent);
38
Chapter1‐ 20
ExampleofIntent(3)
• FollowingIntent usesbuilt‐intask(ACTION_VIEW)to
make a phone call
make

a

phone


call
(seenewUrivalue)
Intent myIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("tel:/216 555-1234"));
startActivity(myIntent);
39
IntentFilters
• TheIntentFilter definestherelationshipbetweenthe
Intentandtheapplication.
• IntentFilters canbespecifictothedataportionof
theIntent,theactionportion,orboth.
• IntentFilters alsocontainafieldknownasacategory.
Acategoryhelpsclassifytheaction.
• Forexample,thecategorynamed
CATEGORY_LAUNCHER
instructsAndroidthattheActivitycontainingthis
IntentFilter shouldbevisibleinthehomescreen.
40
Chapter1‐ 21
IntentFilters
• WhenanIntent isdispatched,thesystemevaluates
theavailableActivities,Services,andregistered
BroadcastReceivers androutestheIntenttothemost
appropriate recipient(seenextFigure).
41
IntentFilters
42
Chapter1‐ 22

IntentFilters
• Toinformthes
y
stemwhichim
p
licit intentsthe
y
can
y
p
y
handle,activities,services,andbroadcastreceivers can
haveoneormoreintentfilters.
• Eachfilterdescribesacapabilitythatthecomponentis
willingtoreceive.
43
• Anexplicit intentisalwaysdeliveredtoitstarget,nomatter
whatitcontains;thefilterisnotconsulted.
• Butanimplicitintentisdeliveredtoacomponentonlyifit
canpassthroughoneofthecomponent'sfilters.
IntentFilters
• IntentFilters a reoftendefinedinana
pp
lication’s
pp
AndroidManifest.xmlwiththe<intent‐filter> tag.
<intent‐filter...>
<actionandroid:name="codeandroid.intent.action.MAIN"/>
<categoryandroid:name="codeandroid.intent.category.LAUNCHER"/>
<categoryandroid:name="android.intent.category.BROWSABLE"/>

<dataandroid: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>
Chapter1‐ 23
AndroidApplications
• EachAndroid applicationrunsinitsownLinux
process.
• Anapplicationconsistsofacombinationofsoftware

componentsincluding:
– Activities
– Services

BroadcastReceivers
– ContentProviders
45
AndroidApplications
Structureof
til
a
t
yp
i
ca
l

Android
Application
46
Chapter1‐ 24
AndroidServices
• AService isanapplicationcomponentthatruns
in the background not interacting with the user
in

the

background
,

not

interacting

with

the

user
,
foranindefiniteperiodoftime.
• Eachserviceclassmusthav e acorresponding
<service> declarationinitspackage's
AndroidManifest.xml.

Services can be started/stopped with
Services

can

be

started/stopped

with

– Context.startService()and
– Context.bindService().
– stopService(…)andunbindService(…)
47

AndroidServices
• Services,likeotherapplicationobjects,runin
th i th d f th i hti
th
ema
i
n
th
rea
d
o
f

th
e
i
r
h
os
ti
ngprocess.
• Thismeansthat,ifyourserviceisgoingtodo
anyCPUintensive(suchasMP3playback)or
blocking (such as networking RSS exchange)
blocking

(such

as


networking
,
RSS

exchange)

operations,itshouldspawnitsownthreadin
whichtodothatwork
48
Chapter1‐ 25
AndroidServices
Service1Class
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
AndroidServices
//Service1Driver
packagematos.service;
dd
importan
d
roi
d
.app.Activity;
importandroid.content.Intent;
importandroid.os.Bundle;
publicclassService1Driver extendsActivity{
@Override
publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//invokingtheservice
Intentservice1Intent=newIntent(this,Service1.class);
startService(service1Intent);
//dosomeworkhere….
}
}//Service1Driver
50

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×