Python for Android
Your Android emulator now is ready to run your custom Python script, so let's create one. Before you do though, note that the published SL4A API is a subset of the full Android API, so certain features either are not available, in the process of being made available or fully supported (see Resources for a link to the current list). Don't let this put you off. What's there is more than enough to produce usable Android apps in Python.
To get a feel for Python running on SL4A, let's port an existing script to the phone. The script in question is based on some code from Chapter 2 of O'Reilly Media's Head First Programming, which I cowrote with David Griffiths in 2009. This simple script connects to the Web site of a fictitious company called Beans'R'Us to grab the company's home page and extract the current price of coffee beans from the page's HTML. The code is straightforward, grabbing the HTML page from the server, searching for the pricing data, extracting it from the HTML page and then displaying it on screen:
from urllib import urlencode from urllib2 import urlopen pg = urlopen("http://www.beans-r-us.biz/prices.html") text = pg.read().decode("utf8") where = text.find('>$') start_of_price = where + 2 end_of_price = start_of_price + 4 price = float(text[start_of_price:end_of_price]) print "The current price of coffee is:", price
This is Python 2 code, which is a deliberate choice, as the Python that comes with SL4A is the 2.6.2 release. To take this program for a spin, either load it into Python's IDLE tool or execute it from the command line:
$ python LJapp-cmd.py The current price of coffee is: 5.52
As you can see, this small script displays the currently published price of coffee beans.
Turning this script into an Android app is just a matter of deciding on the Android UI elements you want to use, as the core functionality does not need to change. The Python on SL4A is fully functional, so the facilities you are used to with standard Python also are available on your smartphone.
To make this script more Android-like, let's display a friendly message on startup as well as one on exit. The makeToast() API call provides this functionality.
The dialogCreateSpinnerProgress() API call lets you display an Android spinner dialog, assuming you then remember to call the dialogShow() API call to make it visible. Let's display a spinner prior to requesting the Web page from the Beans'R'Us server, then dismiss the spinner dialog with the dialogDismiss() API call, once we have the data processed. And, let's vibrate the phone at this point too, just for the fun of it.
To conclude the script, use the dialogCreateAlert(), dialogSetItems() and dialogSetPositiveButtonText() API calls to display the price of beans within an Android dialog. To exit, simply tap the OK button.
Here's the Python code from earlier with the calls to the SL4A API added in:
import android from urllib import urlencode from urllib2 import urlopen app = android.Android() app.makeToast("Hello from LJapp") appTitle = "LJapp" appMsg = "Checking the price of coffee..." app.dialogCreateSpinnerProgress(appTitle, appMsg) app.dialogShow() pg = urlopen("http://www.beans-r-us.biz/prices.html") text = pg.read().decode("utf8") where = text.find('>$') start_of_price = where + 2 end_of_price = start_of_price + 4 price = float(text[start_of_price:end_of_price]) app.dialogDismiss() app.vibrate() appMsg = "The current price of coffee beans:" app.dialogCreateAlert(appMsg) app.dialogSetItems([price]) app.dialogSetPositiveButtonText('OK') app.dialogShow() resp = app.dialogGetResponse().result app.makeToast("Bye!")
Other than the addition of the Android UI code, no other changes are required to the code from earlier, other than removing the earlier script's call to print (which is no longer required).
To transfer your Python script to the emulator for testing, copy your code file into your Android directory, then use the adb utility within the tools directory to push your file to the SL4A scripts directory on the emulator:
$ tools/adb push LJapp.py /sdcard/sl4a/scripts 6 KB/s (748 bytes in 0.116s)
With the file transferred, check the list of scripts within SL4A and notice the addition of LJapp.py near the top of the list.
Fast/Flexible Linux OS Recovery
On Demand Now
In this live one-hour webinar, learn how to enhance your existing backup strategies for complete disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible full-system recovery solution for UNIX and Linux systems.
Join Linux Journal's Shawn Powers and David Huffman, President/CEO, Storix, Inc.
Free to Linux Journal readers.Register Now!
- Download "Linux Management with Red Hat Satellite: Measuring Business Impact and ROI"
- ServersCheck's Thermal Imaging Camera Sensor
- The Italian Army Switches to LibreOffice
- Linux Mint 18
- Chris Birchall's Re-Engineering Legacy Software (Manning Publications)
- Petros Koutoupis' RapidDisk
- Oracle vs. Google: Round 2
- The FBI and the Mozilla Foundation Lock Horns over Known Security Hole
- Privacy and the New Math
Until recently, IBM’s Power Platform was looked upon as being the system that hosted IBM’s flavor of UNIX and proprietary operating system called IBM i. These servers often are found in medium-size businesses running ERP, CRM and financials for on-premise customers. By enabling the Power platform to run the Linux OS, IBM now has positioned Power to be the platform of choice for those already running Linux that are facing scalability issues, especially customers looking at analytics, big data or cloud computing.
￼Running Linux on IBM’s Power hardware offers some obvious benefits, including improved processing speed and memory bandwidth, inherent security, and simpler deployment and management. But if you look beyond the impressive architecture, you’ll also find an open ecosystem that has given rise to a strong, innovative community, as well as an inventory of system and network management applications that really help leverage the benefits offered by running Linux on Power.Get the Guide