Back to Home

Build Your First PHP for Android Application

android · sdk · php for android · scripting layer

Build Your First PHP for Android Application

Original author: Keith Vance
  • Transfer
Android operating system shocked the smartphone market :). Unlike Apple, which has rather strict requirements for developers who want to display their applications on the iPhone App Store, Google created the Android platform open (in the original wide open). You can currently write PHP applications. The guys from Irontech have created the necessary, and using the Scripting Layer for Android (SL4A), you can create PHP applications for Android.

Not!
In this article I will tell you how to install, configure and use PHP for Android and SL4A, we will also see demo applications and you will get the first experience in developing Android applications for PHP.

Install PHP for Android

To install PHP for Android, you must have a phone or emulator supporting Android version 1.5 or greater, also in the application installation settings, there should be a checkmark on installing applications from unknown sources. After all this, just install the two packages of SL4A environment and PHP for Android APK .

Installing SL4A is quite simple, however, after installing the PHP for Android application package, you need to run it and click “install” for a full installation ( During the installation, the program downloads somewhere around 2 MB ). If you have problems installing, then there is a video demonstration on Vimeo (( or here )).

Setting up the PHP development environment for Android

If you installed PHP for Android, theoretically, you can write applications on your phone. But from a practical point of view, this would not be a good idea. What you have to do is download the Android SDK , install the emulator and start writing code using your favorite editor.

After downloading the SDK, unzip the contents, launch the Android application located in the tools directory, and install the emulator. In the Android SDK and AVD Manager menu, select Virtual Devices and click on the New button. Name your emulator (for example, “Droid2”) and select Android 2.2. Enter 10 MB as the size of the SD Card and click Create AVD.

Now you have the emulator configured, click the Start button. There is some difficulty here; you cannot just copy files to the virtual device you just created. You need to configure port forwarding and put your PHP script on a virtual device using a program called adb, which is part of the Android SDK. It is also located in the tools directory.

Next, you start the server on your virtual device, connect to the server to transfer your script. The following steps will help you get everything as fast as possible. (You can read the full documentation of this process here ).

On your running virtual device, go to the Applications screen and press SL4A.
# on the SL4A screen, press the Menu button, select View and select Interpreters.
# Press Menu again, select Start Server and select Private.
# Lower the notification area (Android notification bar) down and you will see the SL4A Service. (Click on the service and write down the port number that your server is listening on, for example 47000.)
# Open a command prompt and set up port forwarding using the adb command. For example, enter the command “adb forward tcp: 9999 tcp: 47000” (replace 47000 with your port number).
# Set the environment variable AP_PORT. On UNIX or Mac, run “export AP_PORT = 9999”. On Windows, "set AP_PORT = 9999."
# To test the emulator, run “run adb push my_script.php / sdcard / sl4a / scripts” (replace my_script.php with the name of your script).

You can also work with a real phone. Follow the same steps as with the emulator. To facilitate the process, set the ANDROID_HOME environment variable, which will indicate the location of your Android SDK and add the path to the tools directory to the list of paths ( something I didn’t really understand how to do this on the phone, if readers know, let them write in the comments )

Creation Android applications in PHP

Writing applications in PHP is a very easy process after you have configured everything described above. The only thing worth noting is that the version of PHP for Android is very truncated. At your disposal will be the basic functions of PHP and JSON support. And if you are an Android developer who is well acquainted with the Java framework for Android, you will notice that the Scripting Layer for Android does not provide access to all the components that you would get using Java development ( we hope that this is only for now ).

What SL4A provides is just a facade to a subset of the Android API. (A complete list of the methods provided by SL4A is available here.) What's the catch of PHP for Android - you can easily develop an application and see how it works by writing just a few lines of code. Let's look at an application that works with quotes, which takes less than 60 lines of code.

  1. define('QUOTE_SERVER', 'http://quoter.take88.com/?ticker=%s');
  2. require_once("Android.php");
  3. $droid = new Android();
  4. $action = 'get_tickers';
  5. $tickers = '';
  6. while (TRUE) {
  7.   switch ($action) {
  8.   case 'quote':
  9.   $droid->dialogCreateSpinnerProgress("Querying stock information server ...", "Please wait");
  10.   $droid->dialogShow();
  11.   $quotes = @array_slice(json_decode(file_get_contents(sprintf(QUOTE_SERVER, $tickers))), 0, 3);
  12.   $droid->vibrate();
  13.   $droid->dialogDismiss();
  14.   // Possible data points.
  15.   // "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"
  16.   $output = '';
  17.   for ($i = 0, $cnt = count($quotes); $i < $cnt; $i++) {
  18.     $output .= "Company: " . $quotes[$i]->NAME ."\n";
  19.     $output .= "Ticker: " . $quotes[$i]->SYMBOL . "\n";
  20.     $output .= "Last trade: $" . $quotes[$i]->LAST_TRADE . "\n";
  21.     $output .= "\n";
  22.   }
  23.     $output = html_entity_decode($output, ENT_QUOTES, "UTF-8");
  24.   // Something is wrong with '
  25.   $output = str_replace("'", "'", $output);
  26.   $droid->dialogCreateAlert("Your stock quotes", $output);
  27.   $droid->dialogSetPositiveButtonText("Get new quote");
  28.   $droid->dialogSetNegativeButtonText("Exit");
  29.   $droid->dialogShow();
  30.   $response = $droid->dialogGetResponse();
  31.   if ($response['result']->which == 'negative') {
  32.     $action = "exit";
  33.   } else {
  34.     $action = 'get_tickers';
  35.   }
  36.   break;
  37.   case 'get_tickers':
  38.   $response = $droid->getInput("Stock Tickers (max. 3)", "Enter Tickers.\nSeparate with spaces.");
  39.   
  40.   $tickers = str_replace(' ', '+', $response['result']);
  41.   $droid->vibrate();
  42.   $action = 'quote';
  43.   break;
  44.   case 'exit':
  45.   $droid->exit();
  46.   exit();
  47.   break;
  48.   }
  49. }
  50. ?>
* This source code was highlighted with Source Code Highlighter.


Copy and paste this code into the editor, save it under the name quoter4android.php and download it in the emulator. If the emulator is not running, start it, configure port forwarding and download quoter4android.php using adb.

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

To install quoter4android.php on your phone, you can configure port forwarding, but it is easier to connect the phone to the computer via USB and copy the script to the sl4a / scripts directory. However, to run the script, you must disconnect it from the computer, otherwise you will not see the installed scripts, then click on the SL4A icon.

Conclusion

With SL4A and PHP for Android, you can do many interesting things; this article is just a small demonstration of the possibilities. All these applications are very young - the new version of SL4A was released when I wrote this article - and in the future we will receive more and more new features.

Read Next