Author Topic: [PYTHON]Android Scripting Environment (SL4A)  (Read 4056 times)

0 Members and 1 Guest are viewing this topic.

Offline techb

  • Soy Sauce Feeler
  • Global Moderator
  • King
  • *
  • Posts: 2350
  • Cookies: 345
  • Aliens do in fact wear hats.
    • View Profile
    • github
[PYTHON]Android Scripting Environment (SL4A)
« on: November 05, 2011, 01:16:18 am »

Didn't know whether to put this in the scripting section on in the mobile section, so here it is.

This will be a quick intro to ASE with some examples.

First, what is ASE aka SL4A?
Android Scripting Environment (ASE from now on) is a way for you to code with scripting languages on your android device directly. You can get different interpreters from Python to PHP. ASE isn't as robust as the actual SDK, but provides it's own api to latch into androids native api. It does this by passing the data back and forth via JSON, I can't give too many details on this for I've never worked with JSON. All I know is, its a way to pack data. For example, much like Python's dictionary's or Pickling.

You can find more information on ASE itself at the google code page found here. In the WiKi section there are tutorials and an API browser you can check out for further information.

Next we need to get ASE.
You can find it in the downloads section from the link above. I would suggest getting the latest version on SL4A which is sl4a_r4.apk. If your phone isn't rooted or doesn't allow third-party app installs, you will need to side load the apk. To do this you will need the Android SDK. The most important thing in the SDK we need is called ADB. You can find adb.bat(windows) in the tools section of the SDK. With the ADB, you can install apps on your phone from your computer. Either put adb on your system path or open a terminal in the dir you found adb in. The command to install .apks is
Code: [Select]
adb install C:\path\to\sl4a_r4.apk
You'll need the correct path to the .apk we downloaded, or move it into the tools dir.
You will need your phone plugged into your computer for this to work, along with the drivers. There is a way to do this via wifi too. You will need a terminal installed on your phone though. And I am not sure if the phone needs to be rooted or not (mine is).
On the phones terminal:
Code: [Select]
setprop service.adb.tcp.port 5555
stop adb
start adb

Now, on the computers terminal in the dir where adb is:
Code: [Select]
adb connect your.ip:5555
Replace "your.ip" with the phones IP address. Example "adb connect 192.168.0.10:5555"

Okay, now that we have the debug bridge, you can install any .apk you have including sl4a. Now that we have sl4a installed, we need an interpreter. I will be using python for these examples. In the interpreter section of sl4a (where you see "shell") press menu-->add-->language of your choice. As with sl4a itself, you might have to side-load the interpreter, if so transfer the .apk to your computer and install it via the method above. Once you have it installed, go ahead and run it. In my case, python, it asks if I want the example scripts and an optional lib install. I chose all of them. As of now, python for android has a working version of the Twisted framework and BeautifSuloup.

Okay, we have everything installed, a working python interpreter and examples to work off of. You can open Python in the interpreter section and start coding right away with instant feedback, or swipe over to the scripts section and hammer out some code there. Menu->add->.py to get a new script.

Now for the actual code and examples.
We will do a simple helloworld first, with some different variations.
Code: [Select]
#import the android object
import android
#create a handle to the object
droid = android.Android()


#call toast from the android facade
droid.makeToast("Hello EvilZone!")

Simple right? How about something a bit more involved:
Code: [Select]
import android
droid = android.Android()


droid.vibrate(400) #in milliseconds


#when getting input and other data returns, it will come back as a list
#with result id, the results, and sometimes other stuff
name = droid.getInput("Name?", "What's your name?")
#print name
name = name.result


droid.ttsSpeak("Hello %s, welcome to SL4A" % name)


As you can see, we can grab and use most of androids api straight from our scripting environment. The second example shows the use of UI. Here comes one of the downfalls of ASE, there is no "real" UI support. You can do the simple stuff like context menus, input, alert dialog, spinners, etc... But can't specify a layout with textviews, buttons, linear/list/grid layouts, or anything like that. And getting the simple UI for menus and whatnot are kind of a drag, because you have to explicitly populate them.  Example UI for a simple WiFI scanner:
Code: [Select]
#imports and get an object of android
import android, time
droid = android.Android()


#scan the wifi and assign vars to hold the results
#this is dirty, making sure WiFi is on, and
#toggling on if not would be better; API Browser =)
droid.wifiStartScan()
ap = droid.wifiGetScanResults()
aps = ap.result


#lists to hold the data from scan
x = []
o = []


#loop through results and grab the data we are interested in
#format the strings to be displayed in the UI
for point in aps:
  x.append(point[“ssid”])
  #capabilities are the encryption, if blank there is no encryption
  if point[“capabilities”] == ““:
    o.append(“MAC: “ point[“bssid”] ”\nFreq: “ str(point[“frequency”]) ”\nEencryp: [OPEN]”)
  else:
    o.append(“MAC: “ point[“bssid”] ”\nFreq: “ str(point[“frequency”]) ”\nEencryp: “ point[“capabilities”])


#set up UI dialog, populate, and present
droid.dialogCreateAlert(“WiFi Scan”, None)
droid.dialogSetItems(x)
droid.dialogShow()
#this grabs what the user has selected
result = droid.dialogGetResponse().result


#if selection not null, create new UI, populate, and present
if result.has_key(“item”):
  item = result[“item”]
  droid.dialogCreateAlert(“Basic Info”, o[item])
  droid.dialogShow()


There is an up side to the UI barrier. You can use HTML and javascript exclusively, or as the front end and pass data back and forth to the backend, in our case python. To do this, we use whats called events.
We need to use postEvent() in javascript and waitForEvent() in python. Example pulled from ASE website (because I'm not a web developer):
Code: [Select]
<html>
  <head>
    <title>Text to Speech</title>
    <script>
      var droid = new Android();
      var speak = function() {
        droid.postEvent("say", document.getElementById("say").value);
      }
    </script>
  </head>
  <body>
    <form onsubmit="speak(); return false;">
      <label for="say">What would you like to say?</label>
      <input type="text" id="say" />
      <input type="submit" value="Speak" />
    </form>
  </body>
</html>

And now the python code to listen for the event and get the data:
Code: [Select]
import android


droid = android.Android()
droid.webViewShow('file:///sdcard/sl4a/scripts/text_to_speech.html')
while True:
  result = droid.waitForEvent('say').result
  droid.ttsSpeak(result['data'])


As you can see, we wrote an HTML file and created a function that uses android to post an event to the system. We then used python to pull that event by its ID from the system event manager and pulled the data from it. You can see we started the HTML from within the python script using webViewShow() method. This works with any html whether we're grabbing data from it or not. All of the scripts and html is saved in sdcard/sl4a/scripts/ by default. If your html file was anywhere diff, the you would have to supply the path.

Well, that's about as much of an introduction as I can give. Anymore and it will be a tutorial on using ASE and the different things you can do with it. Thank you for reading, and any comments or questions are welcome like always. I will provide some links at the bottom here for more information and examples.

LINKS:
IRC example (wordpress doesn't like copy/paste, so any &quot; are meant to be ")
Twisted Framework Spycam
Crack Thomson Speedtouch WPA
ASE for robots
Compile scripts into .apk's for sharing
>>>import this
-----------------------------

Offline FuyuKitsune

  • Knight
  • **
  • Posts: 292
  • Cookies: 21
    • View Profile
Re: [PYTHON]Android Scripting Environment (SL4A)
« Reply #1 on: November 05, 2011, 04:55:30 am »
Damn, I'll have to learn 2.7 syntax :P

Offline techb

  • Soy Sauce Feeler
  • Global Moderator
  • King
  • *
  • Posts: 2350
  • Cookies: 345
  • Aliens do in fact wear hats.
    • View Profile
    • github
Re: [PYTHON]Android Scripting Environment (SL4A)
« Reply #2 on: November 05, 2011, 06:23:08 am »
It's not that diff from 2.6(which I was using), I switched to 2.7 because it supports 64bit OS's. Haven't played with 3.x yet, waiting for some Libs to come out for it.
>>>import this
-----------------------------