A common misconception about developing for the Google Android platform is that you have to write your code in the Java™ language. The truth is, you actually have a multitude of options through the Scripting Layer for Android (SL4A) project. SL4A started out as a 20% project by Google employee Damon Kohler. That was almost two years and four major versions ago.
SL4A provides a platform for several scripting languages, including Beanshell, Lua, Perl, Python, and Rhino. There's also support for basic shell scripting. Today, the Python portion of the SL4A project has developed into a project of its own, due in part to the popularity of Python and the desire to decouple the releases of new Python functionality from the main SL4A release cycle.
This article focuses on using Python to write applications for the Android platform. Python is a great tool for writing both simple scripts and complex, multi-threaded applications. The great thing about having Python on Android is the opportunity to use the untold thousands of lines of code already written and freely available. Python is an easy language to learn if you've never used it before, and you will find many resources available on the Internet to help get you up to speed.
Installation and setup
You must download and install several prerequisites before you can start developing with SL4A. The first is a full Java Development Kit (JDK). You can find the latest version on the Oracle Developer site.
Next you need the Android software development kit (SDK). Two download choices are available on the main Android developer site: a .zip file and an .exe file. When you download and run the .exe file, you'll be presented with a screen where you must choose which versions of the SDK and support files you want to install (see Figure 1).
Figure 1. Choose which Android SDK options you want to download
For this article, I installed and tested everything on a Windows® 7 64-bit machine.
Because this article is about developing applications for the Android platform using Python, you obviously need to install Python on your development machine. Windows does not come with Python installed. As of this writing, the SL4A Python version is 2.6.2. Download either the 32- or 64-bit version of Python 2.6 to stay compatible.
It's a good idea to add a few links to the Android SDK in your PATH statement to make it easier to launch the SDK Manager and other tools. To do this in Windows 7, perform these steps:
- Press the Windows key, and then click Search.
- In the text box, enter Environment.
- Click Edit the system environment variables.
- In the window that opens, click Environment Variables, then select the PATH variable in the User variables list.
- Click Edit, and then add the path to your Android SDK tools directory.
The string you need to add looks like this:
You must add the semicolon (
;) before the new path to
append a new directory. Once that's entered, click OK three times.
Installing SL4A on an Android device is similar to the process for any other Android application. You can scan the QR code on the main SL4A project site with your device to download the SL4A installation file. It should automatically launch when the download is finished. At this point, you should see an installation screen like the one in Figure 2.
Figure 2. SL4A installation screen
Clicking Install starts the process.
The final step is to install the Python interpreter on your device. You can do so using
any of several methods. From the emulator, you can enter
sl4a download in the browser's search box
Figure 3. The SL4A download screen
Clicking the PythonForAndroid_r4.apk link starts the download. To actually launch the installer, view the notification screen by clicking and dragging from the top of the emulator screen toward the bottom of the screen. Clicking the Download complete message launches the Python for Android installer (Figure 4).
Figure 4. Python for Android initial installation screen
Clicking Install launches a process that downloads and unpacks several .zip files. For the purposes of this article, simply click Install on the primary installation screen (Figure 5).
Figure 5. Python for Android primary installation screen
You should see three separate progress windows. The first shows the download, and then the extraction of the files onto the SD card. If everything works, an "Installation Successful" message appears.
Android SDK basics
There are two basic methods for testing your Python code using SL4A: using an emulator or using an actual physical device. The Android SDK provides basic emulator capability and the tools to create an emulated device with the same characteristics as a physical device. In some cases, as with the Samsung tablet add-on, you have a preconfigured emulator available for your use.
The SDK Manager functions as both an update manager and a virtual device creation tool. Each time you launch SDK Manager, it connects to the Android developer site to check for new releases. (You can bypass this process by clicking Cancel.) At this point, you should see the Android SDK and AVD Manager window, shown in Figure 6.
Figure 6. Android SDK and AVD Manager
Selecting Virtual devices in the directory tree displays all previously defined Android virtual devices (AVDs) in the details pane. To create a new emulator device, click New. In the Create New Android Virtual Device (AVD) window, provide the required information in the Name, Target, and SD Card Size fields. Figure 7 shows the entries for my test device. The name must not contain spaces, and you should allow at least 100MB for storage. Choose the appropriate Android version number for your target device. This drop-down list displays only the available options previously downloaded.
Figure 7. The Create New AVD Wizard
Next, click Create AVD. A pop-up window provides the details of your new device. To launch any of the available emulator images, select the desired target, and then click Start. In the Launch Options window, you can proceed with defaults for screen size, or you can select the Scale display to real size check box and choose something larger. A value of 7 seems to work well (see Figure 8). To launch the emulator with a clean slate, select the Wipe user data check box.
Figure 8. AVD launch options
Another indispensable tool provided with the Android SDK is the Android Device Bridge (ADB). This tool provides such functions as installing applications (.apk files), copying files to or from a device, and issuing shell commands on the device. You also use ADB to actually launch SL4A on a device so that you can execute programs from your workstation. To establish communication between your host workstation and a device, you must use ADB to forward TCP/IP traffic from port 9999 to a specific port on the device. Open a Command window, and enter the following command line:
$ adb forward tcp:9999 tcp:42306
The second port number comes from the device. With the latest version of the SL4A, you can set this number in the preferences. For the standard release, you have to use the number SL4A gives you.
Now, launch SL4A, and then click Menu. From the six options at the bottom of the window, click View, then click Interpreters (Figure 9).
Figure 9. Launch a remote server from the SL4A Interpreters menu
Click Menu once more, then click Private to launch a private server.
For a real device, the difference is that Private starts the server using the USB port, and Public uses Wi-Fi. If you view the notifications page again, you'll see that the SL4A service is running (Figure 10).
Figure 10. Android notification screen
Click the message to see the actual port number assigned. In this case, you use port
number 42306 for the second TCP value in the
command. Now, you're ready to actually write some Python code and test it on the
Hello World in Python for Android
It's almost obligatory in any introductory programming article to write a "hello world" program. I do that here to demonstrate the number of ways you can write and test your Python code using SL4A. Here's what the code looks like:
import android droid = android.Android() result = droid.makeToast('Hello, world!')
Every SL4A scripting language uses an import file—android.py for Python, in this case—to set up the interface between the script and the underlying Android application programming interfaces (APIs). You can enter this code directly on your device either in the interpreter (refer back to Figure 9) or by using the editor. To use the interpreter, from the Interpreters screen, launch the Python interpreter by selecting Python 2.6.2. On the resulting screen, you can enter the code above; after the last line, you should see a pop-up window with the words "Hello, world!"
Typing on either an emulated or real device can be tedious. Python's IDLE console and
editor prove indispensable when combined with the ADB tool to write code on a PC
and test it on an Android device. The only thing you'll need is a local copy of the
android.py file. You can either extract it from the python_extras_r14.zip file
available on the SL4A downloads page or transfer it from the device using the
adb pull command. It's also handy to have a directory
named SDCARD at the root of your primary system drive to mirror what's
on your emulated device. This makes things easier from a file path perspective
whenever you run a script on the local machine that needs to access the file system.
Figure 11 shows the Hello World script in the IDLE console.
Figure 11. Hello World in the Python IDLE console
If you launched the server and executed the
command, you should see no error and the "Toast" message shown in
Figure 12. Hello World pop-up message
In Windows, you can launch an edit window in IDLE by clicking File > New Window. This window gives you a complete edit and test capability from your development machine to either an emulated or real Android device.
- Visit the SL4A Google Project site.
- Check out the various SL4A Google groups.
- Learn more at the Python for Android Project page.
- Find the Python resources you need at Python.org.
- Read more developerWorks articles by Paul Ferrill.
- In the developerWorks Open source zone, find hundreds of how-to articles and tutorials, as well as downloads, discussion forums, and a wealth of other resources for developers.
- Check for mobile updates on the developerWorks Mobile development blog.
- You'll find more Android-related articles on developerWorks.
- Stay current with developerWorks technical events and webcasts focused on a variety of IBM products and IT industry topics.
- Attend a free developerWorks Live! briefing to get up-to-speed quickly on IBM products and tools, as well as IT industry trends.
- Watch developerWorks on-demand demos ranging from product installation and setup demos for beginners, to advanced functionality for experienced developers.
- Follow developerWorks on Twitter.
Get products and technologies
- Download SL4A, or visit the unofficial release site.
- Download Python for Android.
- Download the Android SDK.
- Download the latest JDK.
- Download and try the IBM Mobile Technology Preview, a set of code samples and services to help you get started building mobile applications that extend and integrate into the enterprise. The preview includes a RESTful notification service; PhoneGap, an open source framework for building hybrid mobile apps; a lightweight WebSphere Application Server runtime; and sample code to let you see how it all works.
- IBM WebSphere Application Server Feature Pack for Web 2.0 and Mobile includes the IBM Dojo 1.7 Toolkit, new mobile and rich Internet application (RIA) building blocks, and a Dojo-based diagram component. With accompanying Rational tools, the Feature Pack helps you take WebSphere applications developed originally for desktop browsers and adapt and deploy them to mobile devices.
- Evaluate IBM products in the way that suits you best: Download a product trial, try a product online, use a product in a cloud environment, or spend a few hours in the SOA Sandbox learning how to implement Service Oriented Architecture efficiently.
- Get involved in the developerWorks community. Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis.
Dig deeper into Mobile development on developerWorks
Get samples, articles, product docs, and community resources to help build, deploy, and manage your cloud apps.
Innovations in tools and technologies for mobile development.
Software development in the cloud. Register today to create a project.
Evaluate IBM software and solutions, and transform challenges into opportunities.