mo python sl4a 1 pdf

16
© Copyright IBM Corporation 2011 Trademarks Android applications using Python and SL4A, Part 1: Set up your development environment Page 1 of 16 Android applications using Python and SL4A, Part 1: Set up your development environment Configure your Windows workstation to run Scripting Layer for Android Paul Ferrill CTO ATAC Skill Level: Intermediate Date: 19 Dec 2011 This series of articles explores how to use Python and Scripting Layer for Android (SL4A) to build applications for the Google Android platform. This article, the first in the series, shows what you need to do to get everything installed and running. View more content in this series About this series Part 1, this article, kicks off the series by showing you how to install everything necessary to get started writing Python scripts on your Android device. Part 2 will present useful scripting examples to get real work done. It will also explore some of the available Android API calls, including the various windows. Finally, the series will explore how to build a complete user interface just like you would in the Java language. 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

Upload: securedome

Post on 27-Oct-2014

81 views

Category:

Documents


0 download

DESCRIPTION

sl4s python for android

TRANSCRIPT

Page 1: Mo Python Sl4a 1 PDF

© Copyright IBM Corporation 2011 TrademarksAndroid applications using Python and SL4A, Part 1: Setup your development environment

Page 1 of 16

Android applications using Python and SL4A,Part 1: Set up your development environmentConfigure your Windows workstation to run ScriptingLayer for Android

Paul FerrillCTOATAC

Skill Level: Intermediate

Date: 19 Dec 2011

This series of articles explores how to use Python and Scripting Layer for Android(SL4A) to build applications for the Google Android platform. This article, the firstin the series, shows what you need to do to get everything installed and running.

View more content in this series

About this seriesPart 1, this article, kicks off the series by showing you how to installeverything necessary to get started writing Python scripts on your Androiddevice. Part 2 will present useful scripting examples to get real work done.It will also explore some of the available Android API calls, including thevarious windows. Finally, the series will explore how to build a completeuser interface just like you would in the Java language.

A common misconception about developing for the Google Android platform is thatyou have to write your code in the Java™ language. The truth is, you actually havea multitude of options through the Scripting Layer for Android (SL4A) project. SL4Astarted out as a 20% project by Google employee Damon Kohler. That was almosttwo 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, thePython portion of the SL4A project has developed into a project of its own, due in partto the popularity of Python and the desire to decouple the releases of new Pythonfunctionality 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

Page 2: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 2 of 16

applications. The great thing about having Python on Android is the opportunity touse the untold thousands of lines of code already written and freely available. Pythonis an easy language to learn if you've never used it before, and you will find manyresources available on the Internet to help get you up to speed.

Installation and setupYou must download and install several prerequisites before you can start developingwith SL4A. The first is a full Java Development Kit (JDK). You can find the latestversion on the Oracle Developer site.

Next you need the Android software development kit (SDK). Two downloadchoices 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 whereyou must choose which versions of the SDK and support files you want to install (seeFigure 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 platformusing Python, you obviously need to install Python on your development machine.Windows does not come with Python installed. As of this writing, the SL4A Pythonversion is 2.6.2. Download either the 32- or 64-bit version of Python 2.6 to staycompatible.

It's a good idea to add a few links to the Android SDK in your PATH statement tomake it easier to launch the SDK Manager and other tools. To do this in Windows 7,perform these steps:

1. Press the Windows key, and then click Search.

Page 3: Mo Python Sl4a 1 PDF

ibm.com/developerWorks/ developerWorks®

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 3 of 16

2. In the text box, enter Environment.3. Click Edit the system environment variables.4. In the window that opens, click Environment Variables, then select the PATH

variable in the User variables list.5. Click Edit, and then add the path to your Android SDK tools directory.

The string you need to add looks like this:

;C:\Users\paul\Downloads\android-sdk-windows\platform-tools

You must add the semicolon (;) before the new path to append a new directory. Oncethat's entered, click OK three times.

Avoid spaces in directory namesSome of the tools, such as the emulator, may not launch if you install theSDK into a directory with spaces in the name. This includes the defaultlocation of C:\Program Files\android-sdk-windows.

Installing SL4A on an Android device is similar to the process for any other Androidapplication. You can scan the QR code on the main SL4A project site with yourdevice to download the SL4A installation file. It should automatically launch whenthe download is finished. At this point, you should see an installation screen like theone in Figure 2.

Figure 2. SL4A installation screen

Clicking Install starts the process.

Page 4: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 4 of 16

The final step is to install the Python interpreter on your device. You can do sousing any of several methods. From the emulator, you can enter sl4a download in thebrowser's search box (Figure 3).

Figure 3. The SL4A download screen

Clicking the PythonForAndroid_r4.apk link starts the download. To actually launchthe installer, view the notification screen by clicking and dragging from the top of theemulator screen toward the bottom of the screen. Clicking the Download completemessage launches the Python for Android installer (Figure 4).

Page 5: Mo Python Sl4a 1 PDF

ibm.com/developerWorks/ developerWorks®

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 5 of 16

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).

Page 6: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 6 of 16

Figure 5. Python for Android primary installation screen

You should see three separate progress windows. The first shows the download, andthen the extraction of the files onto the SD card. If everything works, an "InstallationSuccessful" message appears.

Android SDK basics

There are two basic methods for testing your Python code using SL4A: using anemulator or using an actual physical device. The Android SDK provides basicemulator capability and the tools to create an emulated device with the samecharacteristics 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 creationtool. Each time you launch SDK Manager, it connects to the Android developer siteto check for new releases. (You can bypass this process by clicking Cancel.) At thispoint, you should see the Android SDK and AVD Manager window, shown in Figure6.

Page 7: Mo Python Sl4a 1 PDF

ibm.com/developerWorks/ developerWorks®

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 7 of 16

Figure 6. Android SDK and AVD Manager

Selecting Virtual devices in the directory tree displays all previously defined Androidvirtual devices (AVDs) in the details pane. To create a new emulator device, clickNew. In the Create New Android Virtual Device (AVD) window, provide the requiredinformation in the Name, Target, and SD Card Size fields. Figure 7 shows theentries for my test device. The name must not contain spaces, and you should allowat least 100MB for storage. Choose the appropriate Android version number foryour target device. This drop-down list displays only the available options previouslydownloaded.

Page 8: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 8 of 16

Figure 7. The Create New AVD Wizard

Next, click Create AVD. A pop-up window provides the details of your new device. Tolaunch any of the available emulator images, select the desired target, and then clickStart. 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 somethinglarger. A value of 7 seems to work well (see Figure 8). To launch the emulator with aclean slate, select the Wipe user data check box.

Page 9: Mo Python Sl4a 1 PDF

ibm.com/developerWorks/ developerWorks®

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 9 of 16

Figure 8. AVD launch options

Another indispensable tool provided with the Android SDK is the Android DeviceBridge (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 alsouse ADB to actually launch SL4A on a device so that you can execute programs fromyour workstation. To establish communication between your host workstation and adevice, you must use ADB to forward TCP/IP traffic from port 9999 to a specific porton 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 touse the number SL4A gives you.

Now, launch SL4A, and then click Menu. From the six options at the bottom of thewindow, click View, then click Interpreters (Figure 9).

Page 10: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 10 of 16

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 theSL4A 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 portnumber 42306 for the second TCP value in the adb forward command. Now, you'reready to actually write some Python code and test it on the device.

Page 11: Mo Python Sl4a 1 PDF

ibm.com/developerWorks/ developerWorks®

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 11 of 16

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 testyour Python code using SL4A. Here's what the code looks like:

import androiddroid = android.Android()result = droid.makeToast('Hello, world!')

Every SL4A scripting language uses an import file—android.py for Python, inthis case—to set up the interface between the script and the underlying Androidapplication programming interfaces (APIs). You can enter this code directly on yourdevice either in the interpreter (refer back to Figure 9) or by using the editor. Touse the interpreter, from the Interpreters screen, launch the Python interpreter byselecting Python 2.6.2. On the resulting screen, you can enter the code above; afterthe 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 consoleand editor prove indispensable when combined with the ADB tool to write code ona PC and test it on an Android device. The only thing you'll need is a local copyof the android.py file. You can either extract it from the python_extras_r14.zip fileavailable on the SL4A downloads page or transfer it from the device using the adbpull command. It's also handy to have a directory named SDCARD at the root ofyour primary system drive to mirror what's on your emulated device. This makesthings easier from a file path perspective whenever you run a script on the localmachine that needs to access the file system. Figure 11 shows the Hello World scriptin the IDLE console.

Page 12: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 12 of 16

Figure 11. Hello World in the Python IDLE console

If you launched the server and executed the adb forward command, you should seeno error and the "Toast" message shown in Figure 12.

Page 13: Mo Python Sl4a 1 PDF

ibm.com/developerWorks/ developerWorks®

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 13 of 16

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 developmentmachine to either an emulated or real Android device.

Page 14: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 14 of 16

ResourcesLearn

• 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 otherresources 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 experienceddevelopers.

• 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 extendand integrate into the enterprise. The preview includes a RESTful notificationservice; PhoneGap, an open source framework for building hybrid mobile apps;a lightweight WebSphere Application Server runtime; and sample code to letyou see how it all works.

• IBM WebSphere Application Server Feature Pack for Web 2.0 and Mobileincludes the IBM Dojo 1.7 Toolkit, new mobile and rich Internet application (RIA)building blocks, and a Dojo-based diagram component. With accompanyingRational tools, the Feature Pack helps you take WebSphere applicationsdeveloped originally for desktop browsers and adapt and deploy them to mobiledevices.

• 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 hoursin the SOA Sandbox learning how to implement Service Oriented Architectureefficiently.

Page 15: Mo Python Sl4a 1 PDF

ibm.com/developerWorks/ developerWorks®

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 15 of 16

Discuss

• Get involved in the developerWorks community. Connect with otherdeveloperWorks users while exploring the developer-driven blogs, forums,groups, and wikis.

Page 16: Mo Python Sl4a 1 PDF

developerWorks® ibm.com/developerWorks/

Android applications using Python and SL4A, Part 1: Setup your development environment

Page 16 of 16

About the author

Paul Ferrill

Paul Ferrill has been writing in the computer trade press for more than20 years. He got his start writing networking reviews for PC Magazineon products like LANtastic and early versions of Novell Netware. Paulholds both BSEE and MSEE degrees and has written software for morecomputer platforms and architectures than he can remember.

© Copyright IBM Corporation 2011(www.ibm.com/legal/copytrade.shtml)Trademarks(www.ibm.com/developerworks/ibm/trademarks/)