100% found this document useful (1 vote)
232 views

Building Cool Scripts, Apps, and Games For Android Smartphones Practical Android Projects Lucas Jordan - Pieter Greyling

This document introduces the Scripting Layer for Android (SL4A), which allows scripts written in various languages like Python, Ruby, and JavaScript to be run on Android devices. SL4A works by running scripting language interpreters on the device and enabling them to access Android APIs via remote procedure calls. It provides a way to quickly develop prototypes, write test scripts, and build utilities by scripting rather than building full Android apps. The document explains how to install SL4A on an emulator, use the included Shell interpreter, and add other interpreters like Python by downloading them from the SL4A website.

Uploaded by

fallulrahman
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
232 views

Building Cool Scripts, Apps, and Games For Android Smartphones Practical Android Projects Lucas Jordan - Pieter Greyling

This document introduces the Scripting Layer for Android (SL4A), which allows scripts written in various languages like Python, Ruby, and JavaScript to be run on Android devices. SL4A works by running scripting language interpreters on the device and enabling them to access Android APIs via remote procedure calls. It provides a way to quickly develop prototypes, write test scripts, and build utilities by scripting rather than building full Android apps. The document explains how to install SL4A on an emulator, use the included Shell interpreter, and add other interpreters like Python by downloading them from the SL4A website.

Uploaded by

fallulrahman
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Buildingcoolscripts,apps,andgamesforAndroidSmartphones PracticalAndroidProjects LucasJordan|PieterGreyling

IntroducingSL4A:
TheScriptingLayerforAndroid ThemainobjectiveofthischapteristointroduceyoutotheScriptingLayerforAndroid (SL4A)platform.OuraimistogiveyouenoughbasicunderstandingofhowSL4A1worksandto beabletouseittorunyourownscriptswritteninanumberofhighlevelscriptinglanguages. Asyouwillsee,thedesignofSL4Aenablesittosupportmanyscriptinglanguageinterpreters.In ordertomakepracticaluseofSL4A,youwillneedtounderstandatleasttherudimentsofone highlevelscriptinglanguagesuchasPython,Ruby,Perl,Lua,JavaScript,orBeanShell. Forthisbook,weassumethatyouhaveagoodlevelofJavaprogramminglanguage knowledgeandthisshouldserveyouwellifyouintendtousearelatedlanguagesuchas BeanShellorJavaScriptwithSL4A. Inthischapter,wewillfirstgiveyousomebackgroundaboutwhatSL4Ais,whatitcanbe usedfor,wheretogetit,andwheretolearnmoreaboutitforyourself.Wewillthenshowyou howtoinstallandrunSL4Awithsmallexamples.Afterthis,youwillgetatechnicaloverviewof howSL4Aworksandhowitsdesignrelatestothescriptingarchitectureswepresentedinthe twopreviouschapters.TohelpyouonyourwaytoadeeperstudyofSL4A,wewillthenshow youhowtoobtainacopyofthecompleteSL4Asourcecoderepository.Inconclusion,wewill presentsomeequivalentSL4AHelloWorldexamplecodesnippetsinvariousscripting languages.

WhatIsScriptingLayerforAndroid?
Inanutshell,SL4Aisaninfrastructureforenablingtheinteroperationofscripting languageenginesthathavebeenportedtotheAndroidplatformwiththeAndroidapplication programminginterface(API)viaremoteprocedurecalls(RPCs)toaserverimplementedasa standardAndroidJavaapplication. AboutSL4A SL4A,2originallycalledAndroidScriptingEnvironment(ASE),wasbroughttousbyDamon Kohler3andishostedonGoogleCodeasanopensourceproject.Fromtheuserperspective, theSL4AAndroidapplicationletsyoueditandrunscriptsagainstmultipleinteractivescript interpretersonyourAndroiddevice.Italsosupportstheabilitytoinstallscriptinterpretersintothe applicationdirectlyfromtheSL4Ahomesite. Inessence,SL4AismorethanjustastandardenduserAndroidapplicationitisalsoaplatform forexposingAndroidfunctionalitytocustomclientprogramssuchasscriptingengines. TheSL4ALicense LiketheAndroidplatform,SL4AisopensourceandisreleasedunderthesameApacheLicense

Version2.0,4asismostofAndroid. UsingSL4A TheSL4Asystemissuitedforthefollowingkindsoftasks:RADprogramming:WithSL4Aitis possibletousearapidapplicationdevelopment(RAD)approachtoquicklycreateaprototype applicationthatallowsyoutotestthefeasibilityofanidea.Oncethepracticalityoftheapplication isconfirmed,youcancreateafullblownAndroidapplication. Writingtestscripts:AssumingthatthesupportingAndroidAPIsareexposedtoSL4A,itcanbe usedtocreatetestscriptsforotherfunctionality. 2http://code.google.com/p/android scripting/ 3http://www.damonkohler.com/search/label/sl4a 4http://www.apache.org/licenses/ CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroidBuildingutilities:Youcanfairly easilyandquicklywriteutilityandtoolscriptsthatdosmalljobsorautomatecertainaspectsof repetitivetasks.Thesetoolsprobablydonotrequireacomplicateduserinterfacetheyneedjust asimpledialogbaseduserinteractionmode.SL4AResources FormorebackgroundonSL4A,werecommendconsultingthefollowingonlineresources: SL4Ahome:http://code.google.com/p/android scripting/ SL4Adownloads: 1. http://code.google.com/p/android scripting/downloads/list 2. http://code.google.com/p/android scripting/downloads/list?q=label:Featured SL4AFAQ: SL4AWiki: http://code.google.com/p/android scripting/w/list SL4Atutorials: 1. http://code.google.com/p/android scripting/wiki/FAQ 2. http://code.google.com/p/android scripting/wiki/Tutorials SL4Asourcecode:http://code.google.com/p/android scripting/source/checkout TheSL4ACodeRepository TheSL4AprojectsourcecodeishostedonGoogleCodeinaMercurialrepository.5Mercurial SCMisanopensource,distributedsource,controlmanagementtool.Mercurialisdesignedto becrossplatformandiswritteninthePythonprogramminglanguage. http://code.google.com/p/android scripting/source/browse/ Laterinthechapter,wewillshowyouhowtousetheMercurialclientsidetoolsand integrateddevelopmentenvironment(IDE)pluginstobringtheSL4Acodetoyour desktopinordertobuildandrunSL4A. RunningSL4AintheAndroidEmulator BeforewediveintothedetailsofSL4A,wewillshowyouthequickestwaytohavea

lookatSL4Ainaction. WewilldownloadtheSL4AAndroidapplicationpackage(APK)distributionandinstallit onarunningAndroidemulatorinstance.ThiswillallowustouseSL4Atoinstallsome scriptingenginesintotheemulatorfromtheSL4Asite. DevelopmentEnvironmentConfiguration Asaquickreference,Table51listssomedevelopmentenvironmentconfiguration settingsandcommandsthatyouwillfindusefulforworkingwiththecodeinthis chapter. Windows EventhoughthePATHentryfortheMercurialexecutable(hgorhg.exe)isnotstrictly necessaryrightnow,itwillbecomeusefulifyoudecidetogetasnapshotoftheSL4A codeandbuildityourself. CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid DownloadingtheSL4AAPKs First,wewilldownloadtheSL4AapplicationarchivefromtheSL4Adownloadsitehere: http://code.google.com/p/android scripting/downloads/list http://code.google.com/p/android scripting/downloads /list?q=label:Featured Orhere: DownloadthelatestreleaseoftheSL4AAPK.Atthetimeofwriting,thiswasthe following: sl4a_r3.apk Savethistoadirectoryonyourfilesystem.Wehavecalledourssl4a apk. AlsoavailableontheSL4AsitewerethefollowingscriptingengineAPKs: beanshell_for_android_r1.apk jruby_for_android_r1.apk lua_for_android_r1.apk perl_for_android_r1.apk python_for_android_r1.apk rhino_for_android_r1.apk NOTE:TheSL4AAPKsareincludedinthebookdownloads,soyoucangetstartedrightaway. InstallingtheSL4AAPKontheAndroidEmulator EnsurethatyouarerunningtheAndroidemulatorusingacompatibleAVD.Forthis, followtheinstructionsinTable51. Now,inaterminalcommandlineshell,navigatetothedirectorywhereyouhavesaved thedownloadedSL4AAPKfileandenterthefollowingcommand: adbinstallsl4a_r3.apk

TheSL4Alaunchericonshouldnowappearontheemulator,asillustratedinFigure51. CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure51.SL4AApplicationLaunchericon RunningSL4AontheAndroidEmulator Whenwelaunchtheapplication,youshouldseetheSL4AprimaryUsageTracking request,asshowninFigure52. Figure52.SL4AUsageTracking SimplyclickoneofeithertheAcceptorRefusebuttons.AfterinvokingtheSL4A applicationmenu(presstheF2keyboardkeywhileintheemulator),youshouldnowsee theimageofthemainSL4AapplicationActivityscreen,asshowninFigure53. CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure53.SL4AapplicationinitialscreenwithMenu NowselecttheViewmenuitemandchoosetheInterpretersentry,asshowninFigure 54. Figure54.SL4Aviewinterpreters AsillustratedinFigure55,ourSL4Aemulatorinstallationiscurrentlyequippedonly withtheShellinterpreter. 199 200 CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure55.SL4Ainterpreters:Shell IfyouruntheShellinterpreter,youshouldbepresentedwithFigure56.Asyoucansee, wehaveenteredthefollowingcommandintotheshell: echo $PATH WearealsoabouttoexecutetheUNIXtopcommand. Figure56.SL4Ainterpreters:Shellcommands TheresultofrunningthetopcommandisshowninFigure57. CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure57.SL4AInterpreters:Shelltop WhenyouexittheShellinterpreterusingtheapplicationmenu,youarepresentedwith thescreenasdepictedinFigure58. ClicktheYesbutton. Figure58.SL4Ainterpreters:Shellexit WearenowdonewithconfirmingthatourSL4Aemulatorinstallationisfunctioning correctly. 201 202 CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid

InstallingSL4AInterpreters NextwewilladdsomenewscriptinglanguageinterpreterstotheSL4Atoolbox. WewillfirstshowyouhowtodosousingtheSL4Aapplicationandthensummarizehow toinstalltheinterpretersfromyourcomputerusingthedownloadable6application packages(APKs).Thiswillenableyoutoinstallthebaseinterpreterenginesslightly fasterthandoingitfromthedeviceusingSL4A.Itisbestthereaftertolettherelevant scriptenginefetchitscurrentandcompatibleextraZIPpackagesunderitsowncontrol. AddingInterpreterswithSL4A FromwithintheInterpretersscreen,selecttheAddmenuitem.Afterscrollingdownto thePythonentryinthelist,youshouldseetheimagedepictedinFigure59. Figure59.SL4AAddinterpreters SelectthePythonentry. ThiswillstartadownloadofthePythonAPKfromtheSL4Asitethatshouldshowthe notificationshowninFigure510whencompleted. 6 http://code.google.com/p/android scripting/downloads/list CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure510.SL4AAddinterpreters:Pythondownloaded ClickingthenotificationentryshoulddisplaythedialogshowninFigure511. Figure511.SL4AAddinterpreters:Pythoninstall NowclicktheInstallbutton. TheimageshowninFigure512iswhatyoushouldseeduringthedownloadand installationprocess. 203 204 CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure512.SL4AAddinterpreters:Pythoninstalling Oncetheinstallationiscomplete,youshouldseesomethingsimilartothatshownin Figure513. Figure513.SL4AAddinterpreters:Pythoninstalled IfyounowclicktheOpenbutton,youwillbepresentedwithascreen(seeFigure514) toinitiatethesecondaryinstallationsequence.Thiswilldownloadallthesupporting archivestotheemulatorinstance. CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure514.SL4AAddinterpreters:InstallPythonsupportingfiles Figure515depictstheprocessofdownloadingthesuiteofPythoninterpreterfiles. Figure515.SL4AAddinterpreters:InstallPythondownloadsupportingfiles Oncethewholeinstallationdownloadprocessiscomplete,youshouldseetheimage illustratedinFigure516. DonotclicktheUninstallbutton. 205 206 CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid

Figure516.SL4AAddinterpreters:InstallPythondone GoingbacktotheSL4Ainterpreterslist,youshouldnowseethePythonscriptlanguage entry,asshowninFigure517. Figure517.SL4AAddinterpreters:Pythoncomplete ThismeansthatyoucanrunPythononAndroid!TheresultofclickingthePython interpreterentryisshowninFigure518. CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure518.SL4A:RunPython Letsentersomecodeintotheinterpreter.TryrunningthefollowingPythonstatements: import sys print(sys.platform) Theresultshouldbethefollowing: linux2 ThisshortsessionisalsoshowninFigure519. Figure519.SL4ARunPythonCode TodemonstrateinteractionwiththeAndroidAPI,enterthefollowingcodeintothe interactiveinterpreter: importandroid andy=android.Android() andy.makeToast('HelloPracticalAndroidProjects!') CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure520.SL4A:RunPythonHelloAndroid ThisconcludesourdemonstrationofhowtoinstallSL4AinterpretersusingSL4A. NOTE:TheSL4Ainterpretersetupprocessthatwehavedocumentedsofarwillalsoapplywhen usingaphysicaldevice.SowhenyouinstallSL4Aandthesupportedinterpretersonyourphone, thesamestepswillbepresented. AddingInterpreterswithPackageArchives Asmentionedearlier,itisalsopossibletoinstalltheinterpretersfromyourcomputer usingthedownloadable7applicationpackages(APKs).Thismakesscriptinterpreter installationslightlyfasterthanonlyusingtheSL4Aapplicationasexplainedbefore. LetsassumethatyouwanttoinstallthePerlscriptinginterpreterinthisfashion.Ina terminalcommandlineshell,navigatetothedirectorywhereyouhavesavedthe downloadedPerlAPKfileandenterthefollowingcommand: AsshownearlierinFigure514whereweinstalledPython,youcannowinitiatethe secondaryinstallationsequenceusingthePerlforAndroidLaunchericonthatshould nowbevisibleintheemulatorordevice.Thiswilldownloadallthesupportingarchives

7 http://code.google.com/p/android scripting/downloads/list CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid followingonfromFigure514withthesameworkflowasbefore.Attheveryleast,it saveshavingtheinterpreterpackagebeingdownloaded. UnderstandingScriptingLayerforAndroid Asmentionedearlier,SL4AenablesinteroperationbetweenAndroidagnosticscripting languageenginesandtheAndroidAPI.Asyouwillseelater,thisisnotrestrictedto scriptinglanguagesonly.AnyprogramthatimplementsacompatibleJSONbasedRPC8 interfacingmoduleorsetofroutinescanpotentiallyinvoketheSL4ARPCServer. CommunicatingUsingJavaScriptObjectNotation(JSON) Internally,SL4AusestheJavaScriptObjectNotation(JSON)dataformatforthe interchangeofmessagesanddatabetweentheSL4ARPCServeranditsclients.Thisis fundamentaltoitsworkingssowewillgiveaquicksummaryofJSONhere. TheacronymJSONwasoriginallyspecifiedbyDouglasCrockford.TheJSONdata formatisdescribedinRFC4627.9 ToquotefromtheJSONspecification: JavaScriptObjectNotation(JSON)isalightweight,textbased, languageindependentdatainterchangeformat.Itwasderivedfromthe ECMAScriptProgrammingLanguageStandard.JSONdefinesasmall setofformattingrulesfortheportablerepresentationofstructureddata. JSONcanrepresentfourprimitivetypes(strings,numbers,booleans, andnull)andtwostructuredtypes(objectsandarrays). Togiveyouanideaofthedataformat,thespecificationalsopresentsanexampleofa JSONobjectasfollows:

REFORMATTHETEXTHERE
WewillnotgointomoredetailaboutJSONherebutinsteadrecommendthatyoufollow uptheonlineresourcesformoreinformationifyouareinterested. SummarizingtheSL4AArchitecture SL4AexposesAndroidAPIfunctionalitytoitsclients.Itachievesthisbyimplementinga scriptinglanguagecompatiblemodulethatmarshalsRPCsandtheirresponsestoand fromaRPCserverimplementedasanAndroidJavaapplication.ThisenablestheRPC servertohavedirectaccesstotheAndroidAPIanditbehavesasaremoteproxyusing afaadethatencapsulatesandexposesselectedAndroidAPIs. Scriptinglanguagesareported,viacrosscompilationorotherwise,totheAndroid platformintheirpurestformavoidinganysourcecodechanges.Thisimpliesthatthe scriptinglanguagehasnoknowledgeoftheAndroidplatformatall.Itgainsaccessto theAndroidAPIusingaspecialmodulegenerallyimplementedinthescriptinglanguage itselfthataccessestheAndroidAPIovertheremoteSL4ARPCserver.Thecurrent implementationusestheJSONdataformatforitsapplicationlayernetworkmessaging

packagepayloadcontent. TheoveralldesignofthisinfrastructureisillustratedinFigure521. Figure521.SL4Aarchitectureoverview Toexplainthingsanotherway,agenericscriptengine,runninginaselfcontained process,accessestheAndroidAPIoverbidirectionalJSONRPCviaanAPIfaade.The faadeisservicedinaseparateprocess,andimplementedasastandard,Java based,Androidserverapplication.ThelatterhasfullaccesstotheAndroidplatformAPI andthusessentiallyservesasaremoteAPIproxyforthescriptingengine/interpreter. EachscriptinglanguagehasawrappermoduleprovidinganAndroidobjectthat CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid servesasaninprocess,local,APIproxy,withthetaskofpackagingRPCcallsas scriptingmethodsinthespiritoftheparticularscriptingengine. Tosumthisup,anoverviewofthefullroundtripinvocationstacklookssomethinglike thefollowing:

Reformatthefollowingtext
GettingtheSL4ASourceCode
ToquotefromthehomesiteofSL4A: "SL4Aisdesignedfordevelopersandisalphaqualitysoftware."Thismeansthatyoucanexpect SL4Atogothroughrelativelyfrequentchangesandreleasesuntilitmovesoutofalpha.Forthis reason,wewillpresentmethodsbywhichyoucanretrievetheSL4Asourcecode. CloningtheSL4ASourceCode WewillshowyouseveraloptionsforgettingalocalcopyoftheSL4Asourcecoderepository. InstallingMercurial WerecommendthatyouinstallalocalcopyofMercurialusingthefollowingresources: Mercurialsourcecodemanagementhome: 1. http://mercurial.selenic.com/ 2. http://mercurial.selenic.com/about/ Mercurialdownloads: 1. http://mercurial.selenic.com/downloads/ Mercurialtools: 1. http://mercurial.selenic.com/wiki/OtherTools

NOTE:TheEclipseIDEpluginforMercurialthatwewillpresentlateralsoincludestheoptionof installingtheMercurialexecutablesandbinariesfortheWindowsplatform.Weprefertoinstall MercurialasastandaloneapplicationandaddittothesystemPATHvariable.

ToverifytheMercurialinstallationonyourdevelopmentcomputer,executethefollowing commandfromtheterminalcommandline: hg v GettingSL4AUsingtheMercurialHgExecutable WeassumethatyouhaveinstalledalocalcopyofMercurialandthatitisonyour systemPATHvariable.Enterintoafilesystemdirectoryofyourchoiceusingthe terminalcommandlineandexecutethefollowingcommand: hg clone https://android scripting.googlecode.com/hg/ android scripting

Thisshouldresultinoutputsomewhatsimilartothefollowing: hg clone https://android scripting.googlecode.com/hg/ android scripting UsingMercurialwithEclipse YoucaninstalltheMercurialpluginforEclipsefromtheupdatelocationbelow: EclipseMercurialplugin: http://javaforge.com/project/HGE EclipseMercurialpluginupdatesite: http://cbes.javaforge.com/update

Figure522displaystheformrequiredforinstallingtheEclipseMercurialplugin. 217 218 CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure522.EclipseMercurialplugin Wewillnotfollowthewholesequencehere,butFigure523displaystheformrequired forcloningaMercurialrepositoryfromwithinEclipse. CHAPTER5:IntroducingSL4A:TheScriptingLayerforAndroid Figure523.CloningaMercurialrepositorywiththeEclipseMercurialplugin UsingMercurialwithIntelliJIDEA YoucaninstalltheMercurialpluginforIntelliJIDEAfromthefollowinglocation: IntelliJIDEAMercurialplugin: http://plugins.intellij.net/plugin/?id=3370

https://bitbucket.org/willemv/hg4idea Figure524displaystheformrequiredforusingtheIntelliJIDEAMercurialplugin.This willallowyoutocloneaMercurialrepositoryfromtheIDE. Figure524.IntelliJIDEAMercurialplugin Again,wewillnotfollowthewholesequencehere,butFigure525displaystheform requiredforcloningaMercurialrepositoryfromwithinIntelliJIDEA. Figure525.CloningaMercurialrepositorywiththeIntelliJIDEAMercurialplugin SL4AHelloWorldExamples TogetanideaofthespiritofSL4A,herearesomebasicexamplesindifferentscripting languages.Installtheinterpretersandtrythemout. BeanShell: source("/sdcard/com.googlecode.bshforandroid/extras/bsh/android.bsh") Python: importandroid andy=android.Android() andy.makeToast("HelloPractical Ruby: droid= Android.new droid.makeToast("HelloPractical

AndroidProjects!")

AndroidProjects!")

TCL: packagerequire android setandroid[androidnew] $androidmakeToast "Hello,Android!" WehopethatthiswillencourageyoutostudySL4Ainmoredepth.

Summary
ThemainobjectiveofthischapterwastointroduceyoutotheScriptingLayerforAndroid(SL4A) platform.SL4Aisagrowingtopicandiswellworthinvestigatingindepth.Wehelpedyougeta basicunderstandingofhowSL4Aworksandtobeabletouseittorunyourownscriptsonthe Androidplatform.YounowhaveenoughinformationtocloneyourowncopyoftheSL4Asource coderepositoryinordertobuildSL4Ayourself. References: 1. http://code.google.com/p/androidscripting/ 2. http://code.google.com/p/androidscripting/ 3. http://code.google.com/p/androidscripting/wiki/Tutorials

4. http://code.google.com/p/androidscripting/wiki/UiExamples 5. http://code.google.com/p/androidscripting/wiki/SharingScripts 6. http://code.google.com/p/androidscripting/

You might also like