http://www.developer.com/ws/android/programming/Build-Your-First-PHP-for-Android-Application-3904261-2.htm

Back to article

Build Your First PHP for Android Application


September 20, 2010

Google's open source Android mobile operating system is taking the smartphone market by storm. Unlike Apple, which has stringent guidelines and requirements for developers who want to offer their applications on the iPhone App Store, Google has left the Android platform wide open. You can even write Android applications in PHP now. The folks at Irontech have created a PHP port to run on Android, and with the Scripting Layer for Android (SL4A), you can build PHP Android applications.

In this article, I'll explain how to install, set up and use PHP for Android and SL4A, I'll present a demo application as an example, and I'll give a first-hand account of the PHP for Android developer experience.

Installing PHP for Android

To install PHP for Android, you have to have a phone or emulator running Android version 1.5 or higher and you must enable "Unknown Sources" under Application settings. After you have that set, you simply install the SL4A environment and the PHP for Android APK.

Installing the SL4A is straightforward, but after you install the PHP for Android application, you need then click "install" again for it to be fully installed and functioning. If you have trouble with the installation, there's a handy video demonstration available on Vimeo to walk you through the process.

 


Visit the Android Dev Center

 

Setting Up the PHP for Android Development Environment

If you installed PHP for Android, theoretically, you can write PHP Android applications with your phone. But for all practical purposes, that doesn't work very well. What you should do is download the Android SDK, set up an emulator, and write code using your favorite editor.

After you've downloaded the SDK, extract it in a directory of your choosing, run the Android application located in the tools directory, and set up an emulator. From the Android SDK and AVD Manager menu, select Virtual Devices and click the New button. Name your new emulator (e.g. "Droid2") and select Android 2.2 as the target. Enter 10 MiB for SD Card size and click Create AVD.

Now that you've got the Droid emulator set up, click the Start button. Here's where things get a little tricky, because you can't just copy files to the virtual device you just set up. You have to set up port forwarding and push your PHP script to the virtual device using a program called adb, which is part of the Android SDK. It is located in the tools directory too.

Next, you will start a server on the virtual device. You will connect with this server to send your scripts. The following steps will get you up and running as quickly as possible (You can read the full documentation for this process here).

  1. With your new virtual device running, go to the Applications screen and click SL4A.

  2. In the SL4A screen, click the Menu button, select View and choose Interpreters.
  3. Click Menu again, select Start Server and choose Private.
  4. Drag the Android notification bar down and you should see SL4A Service. (Click the service and note the port number your server is listening on, e.g. 47000.)
  5. Open up a shell or command prompt and set up port forwarding using the adb tool. For example, enter the command adb forward tcp:9999 tcp:47000, replacing 47000with your port number.
  6. Set up the AP_PORT environment variable. On UNIX or Mac, run export AP_PORT=9999. On Windows, type set AP_PORT=9999.
  7. To test your script with your emulator, just run adb push my_script.php /sdcard/sl4a/scripts, replacing my_script.php with the script you wrote.

You can also set this up to work with an actual phone. Just follow all of the steps you did with your emulator on your phone. To make things easier, you also should set up an ANDROID_HOME environmental variable that points to your Android SDK location and add the tools subdirectory to your path.

Building an Android Application with PHP

Writing a PHP application to run on Android is really pretty simple after you set up your development environment. One thing you'll notice is that the version of PHP included with PHP for Android is an extremely stripped down build. You basically have the core PHP functions and JSON support -- that's about it. And if you're an Android developer who's familiar with the Java framework, you'll notice that the Scripting Layer for Android doesn't provide access to all of the components you're used to having when building a full-blown Android application with Java.

What SL4A does provide are "facades" to a subset of the Android APIs. (A complete listing of all of the methods available via the SL4A is available here. ) But what's fun about PHP for Android is that you can quickly prototype an application and see it in action with just a few lines of code. I'll demonstrate this with an application for checking stock quotes that's less than 60 lines of code.

<?php
define('QUOTE_SERVER', 'http://quoter.take88.com/?ticker=%s');
require_once("Android.php");
$droid = new Android();
$action = 'get_tickers';
$tickers = '';
while (TRUE) {
switch ($action) {
case 'quote':
$droid->dialogCreateSpinnerProgress("Querying stock information server ...", "Please wait");
$droid->dialogShow();
$quotes = @array_slice(json_decode(file_get_contents(sprintf(QUOTE_SERVER, $tickers))), 0, 3);
$droid->vibrate();
$droid->dialogDismiss();
// Possible data points.
// "SYMBOL","NAME","LAST_TRADE","MORE_INFO","LAST_TRADE_DATE","LAST_TRADE_TIME","OPEN","DAYS_HIGH","DAYS_LOW","DIVIDEND_SHARE","PE_RATIO","52_WEEK_LOW","52_WEEK_HIGH","VOLUME"
$output = '';
for ($i = 0, $cnt = count($quotes); $i < $cnt; $i++) {
$output .= "Company: " . $quotes[$i]->NAME ."\n";
$output .= "Ticker: " . $quotes[$i]->SYMBOL . "\n";
$output .= "Last trade: $" . $quotes[$i]->LAST_TRADE . "\n";
$output .= "\n";
}
$output = html_entity_decode($output, ENT_QUOTES, "UTF-8");
// Something is wrong with '
$output = str_replace("'", "'", $output);
$droid->dialogCreateAlert("Your stock quotes", $output);
$droid->dialogSetPositiveButtonText("Get new quote");
$droid->dialogSetNegativeButtonText("Exit");
$droid->dialogShow();
$response = $droid->dialogGetResponse();
if ($response['result']->which == 'negative') {
$action = "exit";
} else {
$action = 'get_tickers';
}
break;
case 'get_tickers':
$response = $droid->getInput("Stock Tickers (max. 3)", "Enter Tickers.\nSeparate with spaces.");

$tickers = str_replace(' ', '+', $response['result']);
$droid->vibrate();
$action = 'quote';
break;
case 'exit':
$droid->exit();
exit();
break;
}
}
?>

Copy and paste the above code into your editor and save it as quoter4android.php and upload it to your emulator. If your emulator isn't running, fire it up, configure your port forwarding and upload the quoter4android.php file with the adb application included in the Android SDK tools directory.

To run the application in your emulator, go to the Applications screen, click the SL4A icon and click the quoter4android.php option.

To install quoter4android.php on your phone, you can set up port forwarding. But it's easier to just plug the phone into your computer via USB and copy the script into the sl4a/scripts directory. However, to run scripts on your phone, you have to unplug it from your computer or else you won't see any of the installed scripts when you click on the SL4A icon.

You'll notice that the first line of this application sets up a constant QUOTE_SERVER. If you're used to building traditional PHP Web applications, you don't have to worry about distributing your code and making changes to it in the future -- that's not how it works with Android. You have to distribute your actual PHP code. So if you decide to put your PHP Android application in the Android Market and you hardcode a Web address in it that you don't control, your application could break down the road.

For example, this stock quote application actually pulls the stock information from a Yahoo Web service. But rather than hardcoding direct access to Yahoo into the Android application, I created a simple Web service as a link between the Android application and the Yahoo stock service. So now if Yahoo decides to stop offering this service, or if they change the way it's accessed, I can just update my Web service located at quoter.take88.com. The Android code doesn't need to change, and nobody's walking around with a broken application on their phone. Also, by leveraging a Web service, I was able to take some of the complexity out of the Android application and move it to my Web service, where I have access to full-blown languages and not just a stripped down version of PHP. In this case, I wrote the Web service in Perl using mod_perl.

 

Conclusion

There's a lot you can do with the SL4A and PHP for Android; this article only scratches the surface of what's possible. While both projects are very young -- in fact, a new version of SL4A dropped while I was writing this story (feel free to run the newest version) -- as they mature, more possibilities will present themselves. In any case, keep your Android applications small, tight and light.

Code Download

  • Quoter4Android.zip
  • About the Author

    Keith Vance is a software engineer and a journalist. He's been developing web applications professionally since 1997 and he received his journalism degree from the University of Washington in 2008.

    Sitemap | Contact Us