Android Scripting With Python - page 2
Installation and Hello World
When you install the Python interpreter, you get a number of sample programs, or scripts, including the traditional "Hello World" code. The code looks like this:
droid = android.Android()
The makeToast call will display the text in a pop-up dialog box. While you might be able to type a few lines on your mobile phone screen,
you certainly won't be doing any serious coding and debugging that way. Fortunately, you can connect to your phone using either WiFi or USB enabling you to write the code on your desktop and execute it on the phone. This does require the SDK to be installed and uses the Android Debug Bridge (adb) utility found in the /tools directory.
To enable this feature you use the adb tool to forward a dummy IP port to the IP port on the device. This requires the following commands:
$ adb forward tcp:9999 tcp:4321
$ export AP_PORT=9999
The first command forwards the local port 9999 to port 4321 on the device while the second defines an environment variable that will be used later. Now all you have to do is run Python on your desktop machine, import the android.py file and you're off and running.
One nice feature available on the phone is the API browser. This handy tool pops up a listing of all available API calls and what parameters are required. It will even insert the code into the editing window if you touch and hold the desired function. Using the API browser gives you an idea of the kinds of things that you can do with this scripting tool.
Automating the changing of multiple phone settings is simple with a few lines of Python code. One common use case is when you return home and want to set the phone in WiFi mode, turn the screen brightness all the way up and the screen saver off, turn off GPS and Bluetooth on and set the ringer . Here's the code to make that happen:
# This script will turn on the charging profile
droid = android.Android()
SL4A brings the power of Python and multiple other languages to your Android phone. Having the ability to change multiple phone settings with a single action is worth the price of admission. There's a really quick way to make your scripts easy to launch from your Android screen. Simply touch and hold an empty space on one of your screens. Then choose "Add folder" and select the "Scripts" folder. Now all you have to do is touch the folder on the screen, and then the DockProfile.py and your charging profile is all set. Next time we'll take a look at a few really useful scripts along with things like posting your current location to Twitter with a script.
Sponsored by BlackBerry
BlackBerry® Enterprise Server Express enables businesses of any size to quickly and easily get started with the BlackBerry solution. It provides advanced BlackBerry smartphone features with no additional software or user license fees, and works with any Internet-enabled BlackBerry data plan or a BlackBerry enterprise data plan. Download now!