WirelessJavaDevelopingwithJ2ME,
SecondEdition
ISBN:1590590775
byJonathanKnudsen
Apress©2003(384pages)
Thiseditionisupdatedtoincludecoverageof
thenextversionofprogramsformobileJava
devices.MIDP2.0containsmanyexcitingnew
features,suchassoundHTTPSsupport,lotsof
userinterfaceAPIenhancements,aGameAPI,
andmuchmore.
TableofContents
WirelessJavaDevelopingwithJ2ME,SecondEdition
Preface
Chapter1 - Introduction
Chapter2 - BuildingMIDlets
Chapter3 - AllAboutMIDlets
Chapter4 - AlmosttheSameOldStuff
Chapter5 - CreatingaUserInterface
Chapter6 - ListsandForms
Chapter7 - CustomItems
Chapter8 - PersistentStorage
Chapter9 - ConnectingtotheWorld
Chapter10 - ProgrammingaCustomUserInterface
Chapter11 - TheGameAPI
Chapter12 - SoundandMusic
Chapter13 - PerformanceTuning
Chapter14 - ParsingXML
Chapter15 - ProtectingNetworkData
AppendixA - MIDPAPIReference
Index
ListofFigures
ListofTables
ListofListings
ListofSidebars
BackCover
AlthoughJavaisincrediblypopular,thestandard
editionofJavaiswaytoobigandbulkytobuild
applicationsforwirelessdevicessuchasPDAsand
phones.Thus,SunhasreleasedJava2Platform,Micro
Edition(J2ME).J2MEhasthepotentialtobeas
revolutionaryinthewirelessspaceasJavahasbeenin
theserverspace.
WirelessJava:DevelopingwithJ2ME,SecondEditionis
updatedtoincludecoverageofthenextversionof
programsformobileJavadevices.MIDP2.0contains
manyexcitingnewfeatures,suchassoundHTTPS
support,lotsofuserinterfaceAPIenhancements,a
GameAPI,andmuchmore.Also,authorJonathan
Knudsenmakesclearwhatmaterialisnewsoreaders
canstillusethebookforMIDP1.0/CLDC1.0.
AbouttheAuthor
JonathanKnudsenisaJavadeveloperandnoted
authorofseveralbooks,includingWirelessJava:
DevelopingwithJava2,MicroEdition,MobileJava,The
UnofficialGuidetoLEGOMINDSTORMSRobots,
LearningJava,andJava2DGraphics.Jonathanbegan
hisobject-orientedprogrammingcareerinObjective-C
ontheNeXTOS,soonthereaftersufferingthrougha
coupleofpurgatorialyearsinMicrosoft'sVisualC++,
beforegraduatingtoJavain1996.Hehaswritten
extensivelyaboutJavaandLEGOrobots,includingfive
books,amonthlyonlinecolumncalled"Bite-SizeJava,"
andarticlesforJavaWorld,EXE,NZZFolio,andthe
O'ReillyNetwork.Jonathanholdsadegreein
mechanicalengineeringfromPrincetonUniversity.
WirelessJava—DevelopingwithJ2ME,Second
Edition
JONATHANKNUDSEN
Copyright©2003byJonathanKnudsen
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1-59059-077-5
PrintedandboundintheUnitedStatesofAmerica12345678910
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
TechnicalReviewer:MichaelYuan
EditorialDirectors:DanAppleman,GaryCornell,SimonHayes,Martin
Streicher,KarenWatterson,JohnZukowski
ManagingandProductionEditor:GraceWong
CopyEditor:RebeccaRider
Proofreader:GregoryTeague
Compositor:DianaVanWinkle,VanWinkleDesignGroup
Indexer:ValeriePerry
ArtistandCoverDesigner:KurtKrames
ManufacturingManager:TomDebolski
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany
IntheUnitedStates,phone1-800-SPRINGER,email
<>,orvisit.
OutsidetheUnitedStates,fax+496221345229,email
<>,orvisit.
Forinformationontranslations,pleasecontactApressdirectlyat2560
NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930,fax:
510-549-5939,email<>,orvisit
.
Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthornorApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
intheDownloadssection.
ToAndrewandElena
Acknowledgments
ThankstoallthefolksatApressforhelpinggetthisbookdone.Thanksto
GaryCornellfortalkingmeintothisbookinthefirstplace.GraceWong
wasmyprojectmanager,ajobIcouldneverhave.Shewasverynice
aboutallofmydelaysandapleasuretoworkwith.Mycopyeditor,
RebeccaRider,putupwithmyformattingidiosyncrasiesandtightened
thebookupalot.ThankstoMichaelYuanforanexcellenttechnical
review.
MyfamilynowhaspermissiontoslapmeupsidetheheadifIever
considertakingonaprojectlikethisagain.Thankstoeveryone—Kristen,
Daphne,Luke,Andy,andElena—forputtingupwithme.
AbouttheAuthor
JonathanKnudsenistheauthorofseveralotherJavabooks,including
LearningJava,Java2DGraphics,andJavaCryptography.Heisalsothe
authorofTheUnofficialGuidetoLEGOMINDSTORMSRobots,but,
sadly,wasunabletoparlaythatsuccessintoafull-timecareer.Jonathan
haswrittennumerousarticlesaboutJavaandafewaboutLEGOrobots
aswell.Heisthefatheroffourchildrenandenjoysbicyclingandplaying
thepiano.Formoreinformation,see />
Preface
Thisbookdescribeshowtoprogrammobiletelephones,pagers,and
othersmalldevicesusingJavatechnology.ItisabouttheMobile
InformationDeviceProfile(MIDP),whichispartofJava2Platform,Micro
Edition(J2ME).Itisconciseandcomplete,describingallofMIDP,aswell
asmovingintoseveraladvancedtopicslikeXMLandcryptography.
ThissecondeditioncoversMIDP2.0,whichincludesmanyexciting
enhancements.Threeentirelynewchaptershavebeenadded,andthe
restofthebookhasbeenmeticulouslyupdated.
WhoareYou?
You'reprobablyreadingthisbookbecauseyou'reexcitedaboutbuilding
wirelessapplicationswithJava.Thisbookisaimedatpeoplewho
alreadyhaveexperienceprogramminginJava.Ataminimum,you
shouldunderstandtheJavaprogramminglanguageandthe
fundamentalsofobject-orientedprogramming.Somechaptersdelveinto
subjectsthatinthemselvescouldoccupyentirebooks.Thesechapters
includesuggestedreadingifyouwanttogetuptospeedonaparticular
subject.
IfyouareunfamiliarwithJava,Isuggestyoureadanintroductorybookor
takeacourse.LearningJava,SecondEdition(O'Reilly2002)isagood
introductiontoJavaforprogrammerswhoarealreadyexperiencedin
anotherlanguagesuchasCorC++.
TheStructureofthisBook
Thisbookisorganizedintofifteenchaptersandoneappendix.Thereare
basicallythreesections.Thefirsttwochaptersareintroductorymaterial.
Chapters3through12providecompletecoverageoftheMIDPAPIs.
Chapters13through15coveradvancedtopics.Thecompletebreakdown
ofchaptersislistedhere:
Chapter1,"Introduction,"providescontextandmotivationforthe
restofthebook.J2MEisexplainedindetail,graduallyzoomingin
toMIDP.
Chapter2,"BuildingMIDlets,"isintendedtobeateaser.It
includesanexampleapplicationthatallowsyoutolookupthe
definitionsofwordsovertheInternetusinganyMIDPdevice.
Alongthewayyou'lllearnalotaboutdevelopingapplicationsfor
theMIDPplatform.
Chapter3,"AllAboutMIDlets,"goesintodetailaboutthelife
cycleandpackagingofMIDPapplications.Itincludesnew
materialontheMIDP2.0securityarchitecture.
Chapter4,"AlmosttheSameOldStuff,"describesthepiecesof
theMIDPAPIthatwillbefamiliartoJavaprogrammers.
Chapter5,"CreatingaUserInterface,"isthefirstofahandfulof
chaptersdevotedtoMIDP'suser-interfacepackages.Itprovides
anoverviewofMIDP'suser-interfacepackageandgoesinto
detailaboutthesimplevisualcomponents.
Chapter6,"ListsandForms,"picksupwhereChapter5leftoff,
describingMIDP'sadvanceduser-interfacecomponents.
Chapter7,"CustomItems,"showshowtocreateyourownform
itemsinMIDP2.0.
Chapter8,"PersistentStorage,"describesMIDP'smechanismfor
storingdata.
Chapter9,"ConnectingtotheWorld,"containsallthejuicydetails
abouthowMIDPapplicationscansendandreceivedataoverthe
Internet.
Chapter10,"ProgrammingaCustomUserInterface,"describes
thelowlevelAPIthatcanbeusedforspecializedapplicationuser
interfaces.
Chapter11,"TheGameAPI,"describesMIDP2.0'snewfeatures
forcreatinggames,includingspritesandtiledlayers.
Chapter12,"SoundandMusic,"isallaboutMIDP2.0'snew
multimediacapabilities.You'lllearnhowtoproducesimpletones
aswellasplaysampledaudiodata.
Chapter13,"PerformanceTuning,"describestechniquesfor
copingwiththelimitedresourcesthatareavailableonsmall
devices.
Chapter14,"ParsingXML,"examinesthespectrumofsmallXML
parsersthatarecurrentlyavailable.Itdescribeshowtoport
parserstoMIDPandbrieflydiscussestheusageinvolvedwith
eachparser.
Chapter15,"ProtectingNetworkData,"discusseshowtoprotect
valuabledataontheinsecureInternet.Itincludestwosample
applicationsthatdemonstratecryptographictechniquesfor
protectingdata.
Finally,anAppendixcontainsacompleteAPIreferenceforthe
classesandinterfacesthatmakeupMIDP.Themethod
signaturesforthepublicAPIofeachclassandinterfacearelisted
forhandyquickreference.Inthissecondedition,theAPI
referenceisflaggedtomakeiteasytoseewhichmethodsare
newinMIDP2.0.
Chapter1:Introduction
Java™2Platform,MicroEdition(J2ME)isthesecondrevolutioninJava's
shorthistory.WhenJavawasintroducedin1995,itlookedlikethefuture
ofcomputingwasinapplets,smallprogramsthatcouldbedownloaded
andrunondemand.AslowInternetforcedappletsoutofthe
mainstream.Java,asaplatform,didnotreallytakeoffuntiltheadventof
servlets,Javaprogramsthatrunonaserver(essentiallyareplacement
forCGI).Javafurtherexpandedintotheserversideofthings,eventually
pickingupthemonikerofJava2Platform,EnterpriseEdition(J2EE).
Thiswasthefirstrevolution,theblitzofserver-sideJava.
Thesecondrevolutionistheexplosionofsmall-deviceJava,andit's
happeningnow.Themarketforsmalldevicesisexpandingrapidly,and
Javaisimportantfortworeasons.First,developerscanwritecodeand
haveitrunondozensofsmallplatforms,withoutchange.Second,Java
hasimportantsafetyfeaturesfordownloadablecode.
UnderstandingJ2ME
J2MEisn'taspecificpieceofsoftwareorspecification.Allitmeansis
Javaforsmalldevices.Smalldevicesrangeinsizefrompagers,mobile
phones,andpersonaldigitalassistants(PDAs),allthewayuptothings
likeset-topboxesthatarejustshyofbeingdesktopPCs.
J2MEisdividedintoconfigurations,profiles,andoptionalAPIs,which
providespecificinformationaboutAPIsanddifferentfamiliesofdevices.
Aconfigurationisdesignedforaspecifickindofdevicebasedonmemory
constraintsandprocessorpower.ItspecifiesaJavaVirtualMachine
(JVM)thatcanbeeasilyportedtodevicessupportingtheconfiguration.It
alsospecifiessomesubsetoftheJava2Platform,StandardEdition
(J2SE)APIsthatwillbeusedontheplatform,aswellasadditionalAPIs
thatmaybenecessary.
Profilesaremorespecificthanconfigurations.Aprofileisbasedona
configurationandaddsAPIsforuserinterface,persistentstorage,and
whateverelseisnecessarytodeveloprunningapplications.
OptionalAPIsdefinespecificadditionalfunctionalitythatmaybeincluded
inaparticularconfiguration.Thewholecaboodle—configuration,profile,
andoptionalAPIs—thatisimplementedonadeviceiscalledastack.For
example,apossiblefuturedevicestackmightbeCLDC/MIDP+Mobile
MediaAPI.Seethesectionlateronplatformstandardizationfor
informationonJSR185,whichwilldefinestandardJ2MEstacks.
Currently,thereareahandfulofconfigurationsandprofiles,asillustrated
inFigure1-1.
Figure1-1:TheJ2MEuniverse
TheJavaCommunityProcess
TheJavaCommunityProcess(JCP)isdesignedtoensurethatJava
technologyisdevelopedaccordingtocommunityconsensus.The
processisdescribedhere:
/>ConfigurationsandprofilesfirstappearintheworldasJava
SpecificationRequests(JSRs).YoucanseealistofcurrentJSRs
here:
/>
Togiveyouaflavorofwhat'shappeningintheJ2MEworld,Table1-1
showssomeoftheconfigurations,profiles,andoptionalAPIsthatare
availableandunderdevelopment.Thisisnotacomprehensivelist;for
moreinformation,checkouttheJCPwebsiteat />Table1-1:J2MEConfigurations,Profiles,andOptionalAPIs
CONFIGURATIONS
JSR NAME
Connected,Limited
URL
30 Device
Configuration
(CLDC)1.0
/>
Connected,Limited
Device
/>139
Configuration
(CLDC)1.1
36
ConnectedDevice
Configuration
/>
PROFILES
JSR NAME
URL
37
MobileInformation />DeviceProfile1.0
118
MobileInformation />DeviceProfile2.0
75 PDAProfile1.0
/>
46 FoundationProfile
/>
129
PersonalBasis
Profile
62 PersonalProfile
/> />
OPTIONALAPIS
JSR NAME
URL
66
RMIOptional
Package
/>
82
JavaAPIsfor
Bluetooth
/>
120
WirelessMessaging />API
135 MobileMediaAPI
/>
179 LocationAPIfor
J2ME
/>
Configurations
AconfigurationspecifiesaJVMandsomesetofcoreAPIsforaspecific
familyofdevices.Currentlytherearetwo:theConnectedDevice
Configuration(CDC)andtheConnected,LimitedDeviceConfiguration
(CLDC).
ConnectedDeviceConfiguration
Aconnecteddevicehas,ataminimum,512KBofread-onlymemory
(ROM),256KBofrandomaccessmemory(RAM),andsomekindof
networkconnection.TheCDCisdesignedfordevicesliketelevisionsettopboxes,carnavigationsystems,andhighendPDAs.TheCDC
specifiesthatafullJVM(asdefinedintheJavaVirtualMachine
Specification,2ndedition)mustbesupported.
TheconfigurationsandprofilesofJ2MEaregenerallydescribedinterms
oftheirmemorycapacity.UsuallyaminimumamountofROMandRAM
isspecified.Forsmalldevices,itmakessensetothinkintermsofvolatile
andnon-volatilememory.Thenon-volatilememoryiscapableofkeeping
itscontentsintactasthedeviceisturnedonandoff.ROMisonetype,
butnon-volatilememorycouldalsobeflashmemoryorbattery-backed
RAM.Volatilememoryisessentiallyworkspaceanddoesnotmaintainits
contentswhenthedeviceisturnedoff.
TheCDCisbeingdevelopedundertheJavaCommunityProcess.For
moreinformationontheCDC,seeA
Linuxreferenceimplementationisavailable.
TheCDCisthebasisofthePersonalProfilestack.ThePersonalProfile
isthenextgenerationofPersonalJava,aJavaapplicationenvironment
thatissimilartoJDK1.1.8.
Connected,LimitedDeviceConfiguration
CLDCistheconfigurationthatinterestsus,becauseitencompasses
mobilephones,pagers,PDAs,andotherdevicesofsimilarsize.CLDCis
aimedatsmallerdevicesthantheCDC.Thenameisalittlemisleading;
really,theCLDCisdesignedforasmalldevicewithalimitednetwork
connection—"LimitedConnectionDeviceConfiguration"mighthavebeen
moreaccurate.
TheCLDCisdesignedfordeviceswith160KBto512KBofmemory
availablefortheJavaplatform.Ifyou'veeverwatchedJ2SEgobbleup
tensofmegabytesofmemoryonyourdesktopcomputer,you'll
appreciatethechallengeofJ2ME.The"limitedconnection"simplyrefers
toanetworkconnectionthatisintermittentandprobablynotveryfast.
(Mostmobiletelephones,forexample,typicallyachievedataratesof
9.6Kbps.)Betweenthesmallscreensize,limitedmemory,andslow
networkconnection,applicationsdesignedintheCLDCspaceshouldbe
verysparingwiththeuseofthenetworkconnection.
TheCLDCisbasedaroundasmallJVMcalledtheKVM.Itsnamecomes
fromthefactthatitisaJVMwhosesizeismeasuredinkilobytesrather
thanmegabytes.WhiletheCLDCisaspecificationsdocument,theKVM
referstoaspecificpieceofsoftware.[1]Becauseofitssmallsize,the
KVMcan'tdoeverythingaJVMdoesintheJ2SEworld.
Nativemethodscannotbeaddedatruntime.Allnative
functionalityisbuiltintotheKVM.
TheKVMonlyincludesasubsetofthestandardbytecodeverifier.
Thismeansthatthetaskofverifyingclassesissplitbetweenthe
CLDCdeviceandsomeexternalmechanism.Thishasserious
securityimplications,aswe'lldiscusslater.
YoucanfindmoreinformationattheCLDChomepage,
Mostdeployeddevices
implementCLDC1.0,butCLDC1.1isalmostcompleteasthisiswritten.
CLDC1.1includesenhancementstoCLDC1.0,includingsupportfor
floating-pointdatatypes.
PlatformStandardization
Giventheprofusionofconfigurations,profiles,andespeciallyoptional
APIs,howdoyouknowwhatAPIsarelikelytobeavailableontypical
devices?Sun'sanswertothisquestionisJSR185
(impressivelytitledJava
TechnologyfortheWirelessIndustry.Thisspecificationaimsto
standardizesoftwarestackstobringcoherencetotheJ2MEworld.
InthenextgenerationofJ2ME,aconceptcalledBuildingBlocksis
supposedtoreplaceconfigurationsandprofiles.ABuildingBlockisjust
somesubsetofaJ2SEAPI.Forexample,oneBuildingBlockmightbe
createdfromasubsetoftheJ2SEjava.iopackage.Conceptually,a
BuildingBlockrepresentsasmallerchunkofinformationthana
configuration.Profiles,then,willbebuiltontopofasetofBuildingBlocks
ratherthanaconfiguration.
ThedefinitionofBuildingBlocksisaJSR,whichisbrieflydescribedhere:
ProgressonJSR68hasbeenextremely
slowsinceitscreationinJune2000.IsuggestkeepingyoureyesonJSR
185instead.
[1]TheKVMwasoriginallypartoftheSpotlesssystem,aSunresearch
project.See />
Profiles
Aprofileislayeredontopofaconfiguration(andsomeday,perhaps,on
BuildingBlocks),addingtheAPIsandspecificationsnecessaryto
developapplicationsforaspecificfamilyofdevices.
CurrentProfiles
SeveraldifferentprofilesarebeingdevelopedundertheJavaCommunity
Process.Table1-1(shownearlier)providesabird's-eyeview.
TheFoundationProfileisaspecificationfordevicesthatcansupporta
richnetworkedJ2MEenvironment.Itdoesnotsupportauserinterface;
otherprofilescanbelayeredontopoftheFoundationProfiletoadduser
interfacesupportandotherfunctionality.
LayeredontopoftheFoundationProfilearethePersonalBasisProfile
andthePersonalProfile.ThecombinationofCDC+FoundationProfile+
PersonalBasisProfile+PersonalProfileisdesignedasthenext
generationofthePersonalJavaapplicationruntimeenvironment(see
Assuch,thePersonalProfile
hasthespecificgoalofbackwardcompatibilitywithpreviousversionsof
PersonalJava.
ThePDAProfile(PDAP),whichisbuiltonCLDC,isdesignedforpalmtop
deviceswithaminimumof512KBcombinedROMandRAM(anda
maximumof16MB).ItsitsmidwaybetweentheMobileInformation
DeviceProfile(MIDP)andthePersonalProfile.Itincludesanapplication
modelbasedonMIDletsbutusesasubsetoftheJ2SEAbstract
WindowingToolkit(AWT)forgraphicuserinterface.AlthoughthePDAP
specificationisnearlyfinished,tomyknowledgenohardware
manufacturerhasannouncedthatitwillbeimplementingPDAP.The
J2MEworldcurrentlyiscoveredbyMIDPonthesmallendandPersonal
Profileonthehigherend.
MobileInformationDeviceProfile
ThefocusofthisbookistheMobileInformationDeviceProfile(MIDP).
Accordingtothespecification,aMobileInformationDevicehasthe
followingcharacteristics:
128KBofnon-volatilememoryfortheMIDPimplementation
32KBofvolatilememoryfortheruntimeheap
8KBofnon-volatilememoryforpersistentdata
Ascreenofatleast96×54pixels
Somecapacityforinput,eitherbykeypad,keyboard,ortouch
screen
Two-waynetworkconnection,possiblyintermittent
TrytoimagineadevicethatmightbeaMIDPdevice:mobiletelephones
andadvancedpagersarerightinthegroove,butentry-levelPDAscould
alsofitthisdescription.
MoreinformationaboutMIDP,includingalinktotheofficialspecification
document,isat />ThisbookcoversbothMIDP1.0andMIDP2.0.MIDP2.0features
numerousenhancements,includingsupportformultimedia,anewgame
userinterfaceAPI,supportforHTTPSconnection,andotherfeatures.It
isfullybackwardcompatiblewithMIDP1.0.Iwillindicatefeaturesthat
arespecifictoMIDP2.0throughouttherestofthebook.
AnatomyofMIDPApplications
TheAPIsavailabletoaMIDPapplicationcomefrompackagesinboth
CLDCandMIDP,asshowninFigure1-2.Packagesmarkedwitha+are
newinCLDC1.1andMIDP2.0.
Figure1-2:MIDPpackages
CLDCdefinesacoreofAPIs,mostlytakenfromtheJ2SEworld.These
includefundamentallanguageclassesinjava.lang,streamclasses
fromjava.io,andsimplecollectionsfromjava.util.CLDCalso
specifiesageneralizednetworkAPIinjavax.microedition.io.
Note AccordingtotheMIDP2.0specification,MIDP2.0willmost
likelybepairedwithCLDC1.1,althoughitiscertainlypossible
forMIDP2.0tobeimplementedatopCLDC1.0.Thefirst
implementationsofMIDP2.0willbepairedwithCLDC1.0,as
theMIDP2.0specificationisfurtheralongintheJava
CommunityProcessthantheCLDC1.1specification.
Optionally,devicevendorsmayalsosupplyJavaAPIstoaccessdevicespecificfeatures.MIDPdevices,then,willtypicallybeabletorunseveral
differentflavorsofapplications.Figure1-3showsamapofthe
possibilities.
Figure1-3:MIDPsoftwarecomponents
Eachdeviceimplementssomekindofoperatingsystem(OS).Native
applicationsrundirectlyonthislayerandrepresenttheworldasitis
today—manydifferentkindsofdevices,eachwithitsownOSandnative
applications.
LayeredontopofthedeviceOSistheCLDC(includingtheKVM)and
theMIDPAPIs.MIDPapplicationsuseonlytheCLDCandMIDPAPIs.
Device-specificJavaapplicationsmayalsouseJavaAPIssuppliedby
thedevicevendor.
AdvantagesofMIDP
Giventhespectrumofconfigurationsandprofiles,whyisthisbookabout
MIDP?First,MIDPcomesatacriticaltime,atimewhenMIDPdevices,
likemobilephones,areanexplodingmarket.Simultaneously,MIDP
devicesareachievingthekindofprocessingpower,memory
consumption,andInternetconnectivitythatmakesthemanattractive
platformfordistributedapplications.MIDP1.0isalreadydeployedon
millionsofhandsetsallovertheworld,andMIDP2.0holdsmuchpromise
forthefuture.
Second,ofcourse,MIDPisthefirstJ2MEprofilethatisreadyforprime
time.Ifyoureadintothenextchapter,youcanwriteMIDPapplications
today.
Portability
TheadvantageofusingJavaoverusingothertoolsforsmalldevice
applicationdevelopmentisportability.Youcouldwritedeviceapplications
withCorC++,buttheresultwouldbespecifictoasingleplatform.An
applicationwrittenusingtheMIDPAPIswillbedirectlyportabletoany
MIDPdevice.
Ifyou'vebeenfollowingJava'sdevelopmentforanytime,thisshould
soundfamiliar.It'sthesame"WriteOnce,RunAnywhere"(WORA)
mantrathatSun'sbeenrepeatingsince1995.Unfortunately,WORAisa
bitofafour-letterwordfordeveloperswhostruggledwithcross-platform
issuesinJDK1.0andJDK1.1(particularlythebrowser
implementations).WhileJava'scross-platformcapabilitiesinJava2are
generallysuccessful,WORAstillhasthetaintofanunfulfilledpromise.
DoesMIDPdeliverpainlesscross-platformfunctionality?Yes.Therewill
alwaysbeplatform-specificbugsinMIDPimplementations,butIbelieve
MIDPworksasadvertisedbecauseitissomuchsmallerthandesktop
Java.Lesscodemeansfewerbugswhenportingtomultipleplatforms.
Mostofthecross-platformincompatibilitiesofJDK1.0andJDK1.1were
causedbythenightmareoftryingtofitdisparatewindowingsystemsinto
theAWT'speer-basedcomponentarchitecture.MIDPhasnothing
approachingthecomplexityofAWT,whichmeansthere'sanexcellent
possibilitythatMIDPapplicationswillseamlesslyrunonmultiple
platformsrightoutofthestartinggate.Furthermore,whiletheJDK1.0
testsuiteonlyincludedafewdozentests,theMIDPcompatibilitytest
suiteincludesseveralthousandtests.
Security
AsecondcompellingreasonforusingJavaforsmalldevicedevelopment
issecurity.Javaiswellknownforitsabilitytosafelyrundownloaded
codelikeapplets.Thisisaperfectfit—it'seasytoimaginenifty
applicationsdynamicallydownloadingtoyourmobilephone.
Butit'snotquitesucharosypicture.Foronething,theKVMusedinthe
CLDConlyimplementsapartialbytecodeverifier,whichmeansthatpart
oftheimportanttaskofbytecodeverificationisperformedofftheMIDP
device.
Second,theCLDCdoesnotallowforapplication-definedclassloaders.
Thismeansthatanykindofdynamicapplicationdeliveryisdependenton
device-specificmechanisms.Asyou'llsee,applicationdeploymentisnot
specificallydefinedintheCLDCorMIDP.
MIDPapplicationsdoofferoneimportantsecuritypromise:theycan
neverescapefromtheconfinesoftheKVM.Thismeansthat,barring
bugs,aMIDPapplicationwillneverbeabletowritetodevicememory
thatdoesn'tbelongtotheKVM.AMIDPapplicationwillnevermessup
anotherapplicationonthesamedeviceorthedeviceOSitself.[2]Thisis
thekillerfeatureofMIDP.Itallowsmanufacturersandcarrierstoopenup
applicationdevelopmenttotheworld,moreorlessfreefromcertification
andverificationprograms,withoutthefearthatroguecoderswillwrite
applicationsthatcrashphones.
InMIDP2.0,MIDletsuitescanbecryptographicallysigned,thenverified
onthedevice,whichgivesuserssomesecurityaboutexecuting
downloadedcode.Anewpermissionsarchitecturealsoallowstheuserto
denyuntrustedcodeaccesstocertainAPIfeatures.Forexample,ifyou
installasuspicious-lookingMIDletsuiteonyourphone,youcanpreventit