Pro Android Python with SL4A pdf pdf
ook ailable Build Android Apps with Python
Andr oid P ython • • • • • •
SL4A
Pro Android Python with
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
Contents at a Glance
AbouttheAuthor................................................................................... Acknowledgments....................................................................................
Chapter1:Introduction............................................................................ ■
Chapter2:GettingStarted......................................................................... ■
Chapter3:NavigatingtheAndroidSDK.............................................................. ■
Chapter4:DevelopingwithEclipse................................................................. ■
Chapter5:ExploringtheAndroidAPI............................................................... ■
Chapter6:BackgroundScriptingwithPython ■
Chapter7:PythonScriptingUtilities.............................................................. ■
Chapter8:PythonDialogBox–basedGUIs ■
Chapter9:PythonGUIswithHTML................................................................... ■
Chapter10:PackagingandDistributing ■ Index..............................................................................................
C H A P T E R 1
Introduction
Thisbookisaboutwritingreal-worldapplicationsfortheAndroidplatformprimarilyusingthePython languageandalittlebitofJavaScript.WhilethereisnothingwrongwithJava,itreallyisoverkillwhenall youneedtodoisturnonoroffahandfulofsettingsonyourAndroiddevice.TheScriptingLayerfor Android(SL4A)projectwasstartedtomeetthatspecificneed.ThisbookwillintroduceyoutoSL4Aand giveyouthepowertoautomateyourAndroiddeviceinwaysyouneverthoughtpossible.
WhySL4A?
Oneofthefirstquestionsyouprobablyhaveaboutthisbookis,“WhywouldIwanttouseSL4Ainstead ofJava?”Thereareseveralanswerstothatquestion.OneisthatnoteveryoneisafanofJava.TheJava languageistooheavyweightforsomeandisnotentirelyopensource.Italsorequirestheuseofanedit/ compile/rundesignloopthatcanbetediousforsimpleapplications.Anequallylegitimateansweris simply“IwanttouseX”,whereXcouldbeanynumberofpopularlanguages.
Googleprovidesacomprehensivesoftwaredevelopmentkit(SDK)aimedspecificallyatJava developers,andmostapplicationsavailablefromtheAndroidmarketareprobablywritteninJava.I’ll addresstheAndroidSDKinChapter3anduseanumberofthetoolsthatcomewithitthroughoutthe book.
Note SL4AcurrentlysupportsBeanshell,JRuby,Lua,Perl,PHP,Python,andRhino. ■
SL4Aisreallytargetedatanyonelookingforawaytowritesimplescriptstoautomatetasksonan Androiddeviceusinganyofthesupportedlanguages,includingJavathroughBeanshell.Itprovidesan interactiveconsoleinwhichyoucantypeinalineofcodeandimmediatelyseetheresult.Itevenmakes itpossible,inmanycases,toreusecodeyou’vewrittenforadesktopenvironment.Thebottomlineis thatSL4AmakesitpossiblebothtowritecodeforAndroid-baseddevicesinlanguagesotherthanJava andtodoitinamoreinteractiveway.
TheWorldofAndroid
GooglejumpedintotheworldofmobileoperatingsystemsinabigwaywhenitboughtAndroid,Inc.in 2005.It’sreallyprettyamazinghowfarithascomeinsuchashorttime.TheAndroidcommunityishuge andhasspawnedawiderangeofconferences,books,andsupportmaterialsthatareeasilyavailable overtheInternet.
Thisisagoodpointtodefineafewtermsthatyou’llseethroughouttherestofthisbook.Android applicationsaretypicallypackagedinto.apkfiles.Thesearereallyjust.zipfilescontainingeverything neededbytheapplication.Infact,ifyourenamean.apkfileto.zip,youcanopenitwithanyarchive toolandexaminethecontents.
MostAndroiddevicescomefromthemanufacturerwiththesystemsfilesprotectedtopreventany inadvertentormaliciousmanipulation.TheAndroidoperatingsystem(OS)isessentiallyLinuxatthe coreandprovidesmuchofthesamefunctionalityyouwouldfindonanyLinuxdesktop.Thereareways tounlockthesystemareasandprovideroot,orunrestricted,accesstotheentirefilesystemonan Androiddevice.Thisprocessisappropriatelycalledrootingyourdevice,andoncecomplete,thedevice isdescribedasrooted.SL4Adoesnotrequirearooteddevice,butwillworkononeifyouhavechosen thispath.
AndroidApplicationAnatomy
AndroidisbasedontheLinuxoperatingsystem(atthetimeofwriting,version2.6oftheLinuxkernel). Linuxprovidesallthecoreplumbingsuchasdevicedrivers,memoryandprocessmanagement,network stack,andsecurity.Thekernelalsoaddsalayerofabstractionbetweenthehardwareandapplications. Touseananatomicalanalogy,youmightthinkofLinuxastheskeleton,muscles,andorgansofthe Androidbody.
ThenextlayeruptheAndroidstackistheDalvikVirtualMachine(DVM).Thispieceprovidesthe coreJavalanguagesupportandmostofthefunctionalityoftheJavaprogramminglanguage.TheDVMis thebrainsinwhichthemajorityofallprocessingtakesplace.EveryAndroidapplicationrunsinitsown processspaceinaprivateinstanceoftheDVM.Theapplicationframeworkprovidesallthenecessary componentsneededbyanAndroidapplication.FromtheGoogleAndroiddocumentation:
“DevelopershavefullaccesstothesameframeworkAPIsusedbythecoreapplications. Thea pplicationar chitectureis des ignedto sim plifyther euseo fcom ponents.Any application canpubli shit sca pabilities,andany othera pplicationmayth enmake useo ftho se capabilities(s ubjectto securitycon straintsenf orced bythefr amework). Thissamemechanismallowscomponentstobereplacedbytheuser. Underlyingallapplicationsisasetofservicesandsystems,including:
- Arichande xtensibles etofViewsth atcanbeused tobuildanap plication,
includinglis ts,grids,tex tboxes,butt ons,andev enanemb eddablew eb browser
- ContentPr ovidersthat enablea pplicationstoa ccessdat af romother
applications(suchasContacts)ortosharetheirowndata
- AResourceManager,providingaccessto non-coderesourcessuchaslocalized
strings,graphics,andlayoutfiles
• ANotificationManagerthatenablesallapplicationsto displaycustomalerts
inthestatusbar
• AnActivityManagerthatmanages thelifecycleofapplicationsandprovidesa
1 commonnavigationbackstack” - action:Thegeneralactiontobeperformed,suchasVIEW_ACTION,EDIT_ACTION,
- data:Thedatatooperateon,suchasapersonrecordinthecontactsdatabase, expressedasaUniformResourceIdentifier(URI)
- category:Givesadditionalinformationabouttheactiontoexecute.Forexample,
- type:Specifiesanexplicittype(aMIMEtype)oftheintentdata.Normally,the typeisinferredfromthedataitself.Bysettingthisattribute,youdisablethat evaluationandforceanexplicittype.
- component:Specifiesanexplicitnameofacomponentclasstousefortheintent.
- extras:Abundleofanyadditionalinformation.Thiscanbeusedtoprovide extendedinformationtothecomponent.Forexample,ifwehaveanactionto sendane-mailmessage,wecouldalsoincludeextrapiecesofdataheretosupply asubject,body,andsoon.
- startLocating()
- startSensing()
- startTrackingPhoneState()
- startTrackingSignalStrengths() Eachofthesecallswillbegingatheringsometypeofdataandgenerateaneventsuchasa“location” eventora“phone”event.Anyofthesupportedlanguagescanregisteraneventhandlertoprocesseach event.ThestartLocating()calltakestwoparameters,allowingyoutospecifytheminimumdistance andtheminimumtimebetweenupdates.
- list.append(x):Addanitemtotheendofthelist;equivalenttoa[len(a):] = [x].
- list.extend(L):Extendthelistbyappendingalltheitemsinthegivenlist; equivalenttoa[len(a):] = L.
- list.insert(I,x):Insertanitematagivenposition.Thefirstargumentisthe indexoftheelementbeforewhichtoinsert,soa.insert(0, x)insertsatthefront ofthelist,anda.insert(len(a), x)isequivalenttoa.append(x).
- list.remove(x):Removethefirstitemfromthelistwhosevalueisx.Itisanerrorif thereisnosuchitem.
- list.pop([i]):Removetheitematthegivenpositioninthelistandreturnit.Ifno indexisspecified,a.pop()removesandreturnsthelastiteminthelist.(The squarebracketsaroundtheiinthemethodsignaturedenotethattheparameteris optional,notthatyoushouldtypesquarebracketsatthatposition.)Youwillsee thisnotationfrequentlyinthePythonLibraryReference.
- list.index(x):Returntheindexinthelistofthefirstitemwhosevalueisx.Itisan errorifthereisnosuchitem.
- list.count(x):Returnthenumberoftimesxappearsinthelist.
- list.sort:Sorttheitemsofthelist,inplace.
- list.reverse(x):Reversetheelementsofthelist,inplace.
AllAndroidapplicationsarebasedonthreecorecomponents:activities,services,andreceivers. Thesecorecomponentsareactivatedthroughmessagescalledintents.SL4Agivesyouaccesstomuchof thecoreAndroidfunctionalitythroughitsAPIfacade,soit’sagoodideatounderstandsomeofthe basics.Chapters3and5lookattheAndroidSDKandAndroidapplicationprogramminginterface(API) indetail,soI’llsavethespecificsforlater.Fornow,I’llintroduceyoutoactivitiesandintents,astheywill beusedextensively.
Activities
TheAndroiddocumentationdefinesanactivityas“anapplicationcomponentthatprovidesascreen withwhichuserscaninteractinordertodosomething,suchasdialthephone,takeaphoto,sendane- mail,orviewamap.Eachactivityisgivenawindowinwhichtodrawitsuserinterface.Thewindow typicallyfillsthescreenbutmaybesmallerthanthescreenandfloatontopofotherwindows.”
Androidapplicationsconsistofoneormoreactivitieslooselycoupledtogether.Eachapplication willtypicallyhavea“main”activitythatcan,inturn,launchotheractivitiestoaccomplishdifferent functions.
Intents
FromtheGoogledocumentation:“Anintentisasimplemessageobjectthatrepresentsanintentionto dosomething.Forexample,ifyourapplicationwantstodisplayawebpage,itexpressesitsintentto viewtheURIbycreatinganintentinstanceandhandingitofftothesystem.Thesystemlocatessome otherpieceofcode(inthiscase,thebrowser)thatknowshowtohandlethatintentandrunsit.Intents canalsobeusedtobroadcastinterestingevents(suchasanotification)system-wide.”
AnintentcanbeusedwithstartActivitytolaunchanactivity,broadcastIntenttosendittoany interestedBroadcastReceivercomponents,andstartService(Intent)orbindService(Intent, ServiceConnection, int)tocommunicatewithabackgroundservice.Intentsuseprimaryand secondaryattributesthatyoumustprovideintheformofarguments.
Therearetwoprimaryattributes:
MAIN_ACTION,andsoon
1
Therearefourtypesofsecondaryattributes:
LAUNCHER_CATEGORYmeansitshouldappearintheLauncherasatop-level application,whileALTERNATIVE_CATEGORYmeansitshouldbeincludedinalistof alternativeactionstheusercanperformonapieceofdata.
Normallythisisdeterminedbylookingattheotherinformationintheintent(the action,data/type,andcategories)andmatchingthatwithacomponentthatcan handleit.Ifthisattributeisset,noneoftheevaluationisperformed,andthis componentisusedexactlyasis.Byspecifyingthisattribute,alltheotherintent attributesbecomeoptional.
SL4AHistory
SL4AwasfirstannouncedontheGoogleOpenSourcebloginJuneof2009andwasoriginallynamed AndroidScriptingEnvironment(ASE).ItwasprimarilythroughtheeffortsofDamonKohlerthatthis projectcametoseethelightofday.Othershavecontributedalongthewayastheprojecthascontinued tomature.Themostrecentreleaseasofthiswritingisr4,althoughyou’llalsofindexperimentalversions availableontheSL4Awebsite(
SL4AArchitecture
Atitslowestlevel,SL4Aisessentiallyascriptinghost,whichmeansthatasanapplicationithosts differentinterpreterseachofwhichprocessesaspecificlanguage.IfyouweretobrowsetheSL4Asource coderepository,youwouldseeacopyofthesourcetreeofeachlanguage.Thisgetscross-compiledfor theARMarchitectureusingtheAndroidNativeDevelopmentKit(NDK)andloadsasalibrarywhenSL4A launchesaspecificinterpreter.Atthatpoint,thescriptwillbeinterpretedlinebyline.
ThebasicarchitectureofSL4Aissimilartowhatyouwouldseeinadistributedcomputing environment.Figure1-1showsinpictorialformtheflowofexecutionwhenyoulaunchSL4Aandthen runascript(inthiscase,hello.py).EverySL4Ascriptmustimportorsourceanexternalfile,suchas android.pyforPython,whichwilldefineanumberofproxyfunctionsneededtocommunicatewiththe AndroidAPI.
TheactualcommunicationbetweenSL4AandtheunderlyingAndroidoperatingsystemusesa remoteprocedurecall(RPC)mechanismandJavaScriptObjectNotation(JSON).YounormallyfindRPC usedinadistributedarchitectureinwhichinformationispassedbetweenaclientandaserver.Inthe caseofSL4A,theserveristheAndroidOS,andtheclientisanSL4Ascript.Thisaddsalayerofseparation betweenSL4AandtheAndroidOStopreventanymaliciousscriptfromdoinganythingharmful.
SecurityisaconcernandisoneofthereasonsthatSL4AusestheRPCmechanism.Here’showthe SL4Awikidescribesit:
“RPCAuthentication: SL4Aenforcesper-script securitysan dboxingbyrequiringall scriptst obeauthenti catedbythe correspondingRPCserver. Inord erforthe authenticationtosucc eed,ascripthas tosendthecorr ecthand shakese crettoth e correspondingserver.Thisisaccomplishedby:
1. AP_HANDSHAKE environmentvariable. readingthe 2. _authenticate withthe value of AP_HANDSHAKE as an callingth e RPCme thod argument. The _authenticate methodmustbethefi rstRPCcallandshouldtakeplaceduringthe initializationoftheAndr oidlibrary.F or example,seeRhin o’so rPython’sA ndroid 2 module”.
Figure1-1.SL4Aexecutionflowdiagram
2
SL4AConcepts
ThereareanumberofconceptsusedbySL4Athatneedtobeintroducedbeforeweactuallyusethem.At averyhighlevel,SL4Aprovidesanumberoffunctionalpiecesworkinginconcerttogether.Each supportedlanguagehasaninterpreterthathasbeencompiledtorunontheAndroidplatform.Along withtheinterpretersisanabstractionlayerfortheAndroidAPI.Thisabstractionlayerprovidesacalling interfaceinaformexpectedforeachlanguage.Theactualcommunicationbetweentheinterpretersand thenativeAndroidAPIusesinter-processcommunication(IPC)asanextralayerofprotection.Finally, thereissupportforanon-deviceenvironmenttotestscriptsinteractively.
AlthoughFigure1-1showsPythonastheinterpreter,theconceptworksprettymuchthesameforall supportedlanguages.EachinterpreterexecutesthelanguageinitsownprocessuntilanAPIcallismade. ThisisthenpassedalongtotheAndroidOSusingtheRPCmechanism.Allcommunicationbetweenthe interpreterandtheAndroidAPItypicallyusesJSONtopassinformation.
JavaScriptObjectNotation(JSON)
SL4AmakesheavyuseofJSONtopassinformationaround.Youmightwanttovisitthe eifyou’veneverseenJSONbefore.InitssimplestformJSONisjustawayof definingadatastructureoranobjectinmuchthesamewayyouwouldinthecontextofaprogram.For themostpart,youwillseeJSONstructuresappearasaseriesofname/valuepairs.Thenamepartwill alwaysbeastringwhilethevaluecanbeanyJavaScriptobject.
InSL4A,youwillfindthatmanyoftheAPIcallsreturninformationusingJSON.Fortunately,there aremultipleoptionswhenitcomestocreating,parsing,andusingJSON.PythontreatsJSONasafirst- classcitizenwithafulllibraryoftoolstoconvertfromJSONtoothernativePythontypesandbackagain. ThePythonStandardLibrarypprintmoduleisaconvenientwaytodisplaythecontentsofaJSON responseinamorereadableformat.
ThePythonStandardLibraryincludesaJSONmodulewithanumberofmethodstomakehandling JSONmucheasier.BecauseJSONobjectscancontainvirtuallyanytypeofdata,youmustuseencoders anddecoderstogetnativePythondatatypesintoaJSONobject.Thisisdonewiththejson.JSONEncoder andjson.JSONDecodermethods.WhenyoumoveaJSONobjectfromoneplacetoanother,youmust serializeandthendeserializethatobject.Thisrequiresthejson.load()andjson.loads()functionsfor decoding,andjson.dump()plusjson.dumps()forencoding.
TherearealargenumberofwebservicesthathaveadoptedJSONasastandardwaytoimplement anAPI.Here’sonefromYahooforimages: { "Image": { "Width":800, "Height":600, "Title":"View from 15th Floor", "Thumbnail": { "Url":"http:\/\/scd.mm-b1.yimg.com\/image\/481989943", "Height": 125, "Width": "100" }, "IDs":[ 116, 943, 234, 38793 ] } } Events
TheAndroidOSusesaneventqueueasameansofhandlingspecifichardware-generatedactionssuch aswhentheuserpressesoneofthehardwarekeys.Otherpossibilitiesincludeanyofthedevicesensors suchastheaccelerometer,GPSreceiver,lightsensor,magnetometer,andtouchscreen.Eachsensor mustbeexplicitlyturnedonbeforeinformationcanberetrieved.
TheSL4AAPIfacadeprovidesanumberofAPIcallsthatwillinitiatesometypeofactionresultingin anevent.Theseincludethefollowing:
Languages
OneofthethingsthatSL4Abringstothetableislotsoflanguagechoices.Asofthewritingofthisbook, thosechoicesincludeBeanshell,Lua,JRubyPerl,PHP,Python,andRhino(versionsgiveninthe followingsections).Youcanalsowriteorreuseshellscriptsifyoulike.Withoutquestion,themost popularofalltheselanguagesisPython.SupportfortheothershasnotbeennearthelevelofPython,up tothispoint,butitispossibletousethemifyou’resoinclined.
Beanshell2.0b4
Beanshellisaninterestinglanguageinthatit’sbasicallyinterpretedJava.Itkindofbegsthequestionof whyyouwouldwantaninterpretedJavawhenyoucouldjustwritenativeJavausingtheAndroidSDK. TheBeanshellinterpreterdoesprovideaninteractivetooltowriteandtestcode.It’sdefinitelynotgoing tobethefastestcode,butyoumightfinditusefulfortestingcodesnippetswithouttheneedtogo throughthewholecompile/deploy/testcycle.
Examiningtheandroid.bshfileshowsthecodeusedtosetuptheJSONdatastructuresforpassing informationtoandreceivinginformationfromtheAndroidOS.Here’swhatthebasiccallfunction lookslike: call(String method, JSONArray params) { JSONObject request = new JSONObject(); request.put("id", id); request.put("method", method); request.put("params", params); out.write(request.toString() + "\n"); out.flush(); String data = in.readLine();
if (data == null) { return null; } return new JSONObject(data); } Here’sasimplehello_world.bshscript: source("/sdcard/com.googlecode.bshforandroid/extras/bsh/android.bsh"); droid = Android(); droid.call("makeToast", "Hello, Android!");
Lua5.1.4
Lua.orgdescribesLuaas“anextensionprogramminglanguagedesignedtosupportgeneralprocedural 3 programmingwithdatadescriptionfacilities”. Thetermextensionprogramminglanguagemeansthat Luaisintendedtobeusedtoextendanexistingprogramthroughscripting.Thisfitsinwellwiththe conceptofSL4A.
Fromasyntaxperspective,LuaresemblesPythonsomewhatinthatitdoesn’tusecurlybracesto wrapcodeblocksorrequireasemicolonforstatementtermination,althoughyoucandothisifyouwant to.Inthecaseofafunctiondefinition,Luausesthereservedwordfunctiontobeginthecodeblockand thenthereservedwordendtomarktheend.
Luahasmostofthestandarddatatypesyouwouldexpectinamodernlanguageandalsoincludes theconceptofatable.InLua,atableisadynamicallycreatedobjectthatcanbemanipulatedmuchlike pointersinconventionallanguages.Tablesmustbeexplicitlycreatedbeforeuse.Tablescanalsoreferto othertables,makingthemwellsuitedtorecursivedatatypes.Thelistofgenericfunctionsfor manipulatingtablesincludestable.concat,.insert,.maxn,.remove,and.sort.
FromtheLuawebsite,here’sashortLuacodesnippetthatcreatesacircularlinkedlist: list = {} -- creates an empty table current = list i = 0 while i < 10 do current.value = i current.next = {} current = current.next i = i+1 end current.value = i acurrent.next = list
3
Here’stheLuacodethatimplementstheRPCcallfunction: function rpc(client, method, ...) assert(method, 'method param is nil') local rpc = { ['id'] = id, ['method'] = method, params = arg } local request = json.encode(rpc) client:send(request .. '\n') id = id + 1 local response = client:receive('*l') local result = json.decode(response) if result.error ~= nil then print(result.error) end return result end
TheobligatoryLuahelloworldscript: require "android" name = android.getInput("Hello!", "What is your name?") android.printDict(name) -- A convenience method for inspecting dicts (tables). android.makeToast("Hello, " .. name.result)
TheLuawikihaslinkstosamplecodewithalargenumberofusefulsnippets.
Perl5.10.1
PerlprobablyqualifiesastheoldestofthelanguagesavailableinSL4Aifyoudon’tcounttheshell.It datesbackto1987andhasbeenusedinjustabouteverytypeofcomputingapplicationyoucanthinkof. ThebiggestadvantageofusingPerlisthelargenumberofcodeexamplestodrawfrom.Codingthe hello_world.plscriptlooksalotlikethatofotherlanguages: use Android; my $a = Android->new(); $a->makeToast("Hello, Android!");
Here’sthePerlcodeneededtolaunchanSL4Ascript: # Given a method and parameters, call the server with JSON, # and return the parsed the response JSON. If the server side # looks to be dead, close the connection and return undef. sub do_rpc { my $self = shift; if ($self->trace) { show_trace(qq[do_rpc: $self: @_]); }
my $method = pop; my $request = to_json({ id => $self->{id}, method => $method, params => [ @_ ] }); if (defined $self->{conn}) { print { $self->{conn} } $request, "\n"; if ($self->trace) { show_trace(qq[client: sent: "$request"]); } $self->{id}++; my $response = readline($self->{conn}); chomp $response; if ($self->trace) { show_trace(qq[client: rcvd: "$response"]); } if (defined $response && length $response) { my $result = from_json($response); my $success = 0; my $error; if (defined $result) { if (ref $result eq 'HASH') { if (defined $result->{error}) { $error = to_json( { error => $result->{error} } ); } else { $success = 1; } } else { $error = "illegal JSON reply: $result"; } } unless ($success || defined $error) { $error = "unknown JSON error"; } if (defined $error) { printf STDERR "$0: client: error: %s\n", $error; } if ($Opt{trace}) { print STDERR Data::Dumper->Dump([$result], [qw(result)]); } return $result; } } $self->close; return; }
PHP5.3.3
PHPis,withoutadoubt,oneofthemostsuccessfulgeneral-purposescriptinglanguagesforcreating dynamicwebpages.FromhumblebeginningsasthePersonalHomePage,theacronymPHPnowstands forPHP:HypertextPreprocessor.PHPisafreeandopensourcelanguagewithimplementationsfor virtuallyeverymajoroperatingsystemavailablefreeofcharge.
Here’sthePHPcodeneededtolaunchanSL4AscriptviaanRPC: public function rpc($method, $args) { $data = array( 'id'=>$this->_id, 'method'=>$method, 'params'=>$args ); $request = json_encode($data); $request .= "\n"; $sent = socket_write($this->_socket, $request, strlen($request)); $response = socket_read($this->_socket, 1024, PHP_NORMAL_READ) or die("Could not read input\n"); $this->_id++; $result = json_decode($response); $ret = array ('id' => $result->id, 'result' => $result->result, 'error' => $result->error ); return $ret; }
ThePHPversionofhello_world.phplookslikethis: <?php require_once("Android.php"); $droid = new Android(); $name = $droid->getInput("Hi!", "What is your name?"); $droid->makeToast('Hello, ' . $name['result']);
YougetanumberofotherexamplescriptswhenyouinstallPHPalongwiththebasic hello_world.php.
Rhino1.7R2
TheRhinointerpretergivesyouawaytowritestand-aloneJavaScriptcode.JavaScriptisactually interpreteraremany.IfyouplanonbuildinganytypeofcustomuserinterfaceusingHTMLand JavaScript,youcouldprototypetheJavaScriptpartandtestitwiththeRhinointerpreter.
Theandroid.jsfileforRhinoresemblesthatoftheotherlanguagesinmanyaspects.Here’swhat theRPCcalldefinitionlookslike: this.rpc = function(method, args) { this.id += 1; var request = JSON.stringify({'id': this.id, 'method': method, 'params': args}); this.output.write(request + '\n'); this.output.flush(); var response = this.input.readLine(); return eval("(" + response + ")"); },
Here’sasimpleRhinohello_world.jsscript: load("/sdcard/sl4a/extras/rhino/android.js"); var droid = new Android(); droid.makeToast("Hello, Android!");
JRuby1.4
Oneofthepotentialhazardsofanyopensourceprojectisneglect.Atthetimeofthiswriting,basedon SL4Ar4,theJRubyinterpreterhassufferedfromneglectanddoesn’tevenrunthehello_world.rbscript. Inanycase,here’swhatthatscriptlookslike: require "android" droid = Android.new droid.makeToast "Hello, Android!"
TheJRubyinterpreterdoeslaunch,andyoucantryoutsomebasicJRubycodewithit.Here’swhat theAndroidclasslookslikeinRuby: class Android def initialize() @client = TCPSocket.new('localhost', AP_PORT) @id = 0 end def rpc(method, *args) @id += 1 request = {'id' => @id, 'method' => method, 'params' => args}.to_json() @client.puts request response = @client.gets() return JSON.parse(response) end def method_missing(method, *args) rpc(method, *args) end end Shell
Ifyou’reashellscriptwizard,thenyou’llfeelrightathomewithSL4A’sshellinterpreter.It’sessentially thesamebashscriptenvironmentyouwouldseeatatypicalLinuxterminalprompt.You’llfindallthe familiarcommandsformanipulatingfileslikecp,ls,mkdir,andmv.
Python
Pythonhasawideusageandheavyfollowing,especiallywithinGoogle.Infact,itsfollowingisso significanttheyhiredtheinventorofthelanguage,GuidovanRossum.Pythonhasbeenaroundforquite awhileandhasmanyopensourceprojectswritteninthelanguage.Italsohasseenthemostinterestas farasSL4Aisconcerned,soyou’llfindmoreexamplesanddiscussionsintheforumsthanforanyofthe otherlanguages.Forthatreason,Iwillspendalittlemoretimeintroducingthelanguage,tryingtohit thehighlightsofthingsthatwillbeimportantfromanSL4Aperspective.
LanguageBasics
KnowingthePythonlanguageisnotanabsoluterequirementforthisbook,butitwillhelp.Thefirst thingyouneedtoknowaboutPythonisthateverythingisanobject.Thesecondthingisthatwhitespace ismeaningfulinPython.Bythat,ImeanPythonuseseithertabsoractualspaces(ASCII32)insteadof curlybracestocontrolcodeexecution(seeFigure1-2).Third,it’simportanttorememberthatPythonis acase-sensitivelanguage.
Figure1-2.ExampleofwhitespaceusageinPython
Pythonisagreatlanguagetousewhenteachingan“introductiontocomputerprogramming” course.EveryinstallationofstandardPythoncomeswithacommand-lineinterpreterwhereyoucan typeinalineofcodeandimmediatelyseetheresult.Tolaunchtheinterpreter,simplyenterpythonata commandprompt(Windows)orterminalwindow(LinuxandMacOSX).Atthispoint,youshouldseea fewlineswithversioninformationfollowedbythetriplearrowprompt(>>>),lettingyouknowthat you’reinsidethePythoninterpreterasshownhere:
C:\Users\paul>python Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> PythonusesanumberofnamingconventionsthatyouwillseeifyouexaminemuchPythoncode.
Thefirstisthedoubleunderscore,whichisusedinPythonto“mangle”orchangenamesasawayto defineprivatevariablesandmethodsusedinsideaclass.Youwillseethisnotationusedfor“special” methodssuchas__init__(self).Ifaclasshasthespecial__init__method,itwillbeinvokedwhenever anewinstantiationofthatclassoccurs.
Forexample: >>> class Point: def __init__(self, x, y): self.x = x self.y = y >>> xy = Point(1,2) >>> xy.x, xy.y (1, 2)
Asyoucanseefromtheexample,selfisusedasareservedwordinPythonandreferstothefirst argumentofamethod.It’sactuallyaPythonconventionand,inreality,hasnospecialmeaningto Python.However,becauseit’sawidelyacceptedconvention,you’llwanttostickwithittoavoidany potentialissues.Technically,selfisareferencetotheclassorfunctionitself.Methodswithinaclass maycallothermethodsinthesameclassbyusingthemethodattributesoftheselfargument.
Pythonhasashortlistofbuilt-inconstants.Themainonesyou’llrunintoareFalse,True,andNone. FalseandTrueareoftypeboolandshowupprimarilyinlogicaltestsortocreateaninfiniteloop.
Oneofthethingsthatfrequentlyconfusesnewusersofthelanguageisthevarietyofdatatypes.The followingsectionsgivequickoverviewofthekeydatatypesyou’llneedtousePythonandSL4A.
Dictionary:AnUnorderedSetofKey/ValuePairsRequiringUniqueKeys
APythondictionarymapsdirectlytoaJSONdatastructure.Thesyntaxfordefiningadictionaryuses curlybracestoencloseentriesandacolonbetweenthekeyandvalue.Here’swhatasimpledictionary definitionlookslike: students = {'barney' : 1001, 'betty' : 1002, 'fred' : 1003, 'wilma' : 1004}
Toreferenceentries,usethekey,asshownhere: students['barney'] = 999 students['betty'] = 1000
Youcanalsousethedict()constructortobuilddictionaries.Whenthekeyisasimplestring,you cancreateanewdictionaryusingargumentspassedtodict()suchasthefollowing: students = dict(barney=1001, betty=1002, fred=1003, wilma=1004)
BecauseeverythinginPythonisanobject,youcanexpecttoseemethodsassociatedwitha dictionaryobject.Asyoumightexpect,therearemethodstoreturnthekeysandthevaluesfroma dictionary.Here’swhatthatwouldlooklikeforthestudentsdictionary: >>> students {'barney': 1001, 'betty': 1002, 'fred': 1003, 'wilma': 1004} >>> students.keys() ['barney', 'betty', 'fred', 'wilma'] >>> students.values() [1001, 1002, 1003, 1004]
Thesquarebracketconventiondenotesalist.Evaluatingthestudents.keys()statementreturnsa listofkeysfromthestudentsdictionary.
List:ABuilt-InPythonSequenceSimilartoanArrayinOtherLanguages
InPython,asequenceisdefinedas“aniterablewhichsupportsefficientelementaccessusinginteger indicesviathe__getitem__()specialmethodanddefinesalen()methodthatreturnsthelengthofthe sequence.”Aniterableisdefinedas“acontainerobjectcapableofreturningitsmembersoneatatime.” Pythonprovidesdirectlanguagesupportforiterationbecauseit’soneofthemorecommonoperations inprogramming.Listobjectsprovideanumberofmethodstomakeworkingwiththemeasier.Fromthe Pythondocumentation: