Saturday, February 12, 2011

How to make an android app with SL4A and Eclipse

Having completed my first python script using sl4a on my HTC Desire I decided the next step was to create an APK (Android PacKage) to make it easier to download and run. The process is not that easy (but easier than writing the whole thing in Java) so the following explains how it was done on my PC running Windows Vista:
  • Download and install JDK from Oracle: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  • Download and install Eclipse Helios: http://www.eclipse.org/downloads/ If you already have Eclipse installed make sure you have the latest updates.
  • Download and install the Android SDK http://developer.android.com/sdk/index.html If you already have the Android SDK installed make sure you have the latest updates.
  • On start up Eclipse will ask you to create a working directory. Once you have done this install the ADT plugin to Eclipse as follows: Select Help > Install New Software. Click Add, in the top-right corner. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:  https://dl-ssl.google.com/android/eclipse/  If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons). Click OK. In the Available Software dialog, select the checkbox next to Developer Tools and click Next. In the next window, you'll see a list of the tools to be downloaded. Click Next. Read and accept the license agreements, then click Finish.When the installation completes, restart Eclipse.
  • In Eclipse click onWindow/Preferences/Android and set the SDK location to where the SDK was installed (probably C:\Program Files\Android\android-sdk-windows).
  • Download and install Hg from mercurial: http://mercurial.selenic.com/wiki/Download 
  • Have a cup of coffee (still some way to go!)
  • Create a clone of the latest sl4a repository: Use windows explorer to create a directory where you will store the clone. Hold down the shift key and right click on the directory then open a command window. In the command window type: hg clone https://rjmatthews62-android-scripting.googlecode.com/hg/ and some time later your clone will be there. The repository gets updated regularly so use 'hg pull -u' to get and update the latest repository. Exit the command window.
  • Open Eclipse and click on File/Import/General/Existing Projects into Workspace/Next and Browse to the cloned directory. Click on Android/OK then select all and click Finish. Your screen should look like this (with lots of errors):                    [Click on view to enlarge]

  • Don't panic! First of all you don't need all projects at this stage so right click and Close Project for python, beanshell, jruby, lua, perl, rhino, tcl, InterpreterForAndroidTemplate and Documentation Generator.
  • Next include ANDROID_SDK in the Classpath Variable list by clicking Windows/Preferences/Java/BuildPathVariables/New. Put ANDROID_SDK for the name and your SDK directory for the folder (probably c:\ProgramFiles\Android\android-sdk-windows).
  • Now click Project/Build Automatically, then Project/Clean/Clean all Projects/OK. If you get error messages of files missing try Project/Build All without cleaning first. If you still have errors check if any projects have .jar entries in their libs folders which have not yet been added to the build path (right click/BuildPath/add to Build Path if not - but don't put in duplicate entries). Then try Project/Clean/Clean all Projects/OK (and maybe once more if you still have errors). Ignore the numerous warnings.
  • All these projects now comprise a working clone of SL4A. To turn your script into an APK make a copy of ScriptForAndroidTemplate (right click/copy then right click/paste into the same area). A new project will appear with the name Copy of ScriptForAndroidTemplate. To connect this project to your clone of SL4A double click on it, right click on build.xml /Run As /Ant Build. Rename the project using Refactor/Rename to whatever name you choose for your project and Refresh/Clean/Build the project.
  • Connect your phone to the PC via the USB cable, press menu, click settings/Connect to PC/Default connection type/Charge only/Done/ then press Home. If you haven't got a suitable phone set up an emulator in the Android SDK and AVD Manager (but be aware the emulator may or may not start at the first attempt and can take 10 to 20 minutes to start working the first time!).
  • Using the phone press menu again, then click settings/Applications/Development/USB debugging/OK/ then press Home. Vista should automatically find the USB driver for the phone.
  • From Eclipse install your cloned version of SL4A on your phone by clicking on ScriptingLayerForAndroid to highlight it, then Run/Run/AndroidApplication/OK.
  • With SL4A installed click on your project to highlight it then Run/Run/AndroidApplication/OK. The Console should inform you of the Android launch and a short time later you should see 'Hello Android' appear briefly on the phone (or emulator) which is the output of the default script.
  • Now you will want to tailor your project. Double click your project/res/drawable. Script_logo_48.png is the 48x48 image file that will display on your phone's screen when installed. Replace it to suit your requirements.
  • Further down from drawable double click values then strings.xml. In the xml display window click on strings.xml and change Dummy Script to your app name (must be less than 10 characters). Right click on the screen and save your change.
  • Next double click on raw and Refactor/Rename to change the name script.py to your_script_name.py then double click src/com.dummy.fooforandroid/Script.java and change  R.raw.script to R.raw.your_script_name and save.
  • Double click on src and Refactor/Rename to change the package name com.dummy.fooforandroid to your.package.name (you must have at least 2 full stops in the name). Do the same for gen (ignore the warning that the name already exists).
  • Now highlight your project then click on Project/Properties/Android select your android target and click OK
  • Towards the bottom of your project list double click on AndroidManifest.xml. Change the package name in the manifest from com.dummy.fooforandroid to your.package.name. Change your minSdkVersion from "4" to suit your android target (this is the API level for your android target shown in Project/Preferences/Android). Uncomment the permissions you require your application to have (take off <!-- at the start and  --> at the end).
  • Right click on your_script_name then open with text editor. Delete the default script, replace it with your own and save. Then Clean/Build/Refresh your project and run it. If all goes well click on File/Export to export your application as an apk. Copy the apk to your phone's sdcard, and use astro to install it.
  • Eclipse will automatically set your project to debuggable. If you want to distribute your apk open the Manifest Application and set debuggable to False. Then export again. Warn users that the interpreter for your script will also be downloaded when they install the apk.
  • All finished! Wasn't that easy!!

38 comments:

  1. Excellent stuff.
    One thing: you suggest pulling the repository from:
    https://rjmatthews62-android-scripting.googlecode.com/hg/

    While this is actually the very latest version at the moment, there's no guarantee that it will always be the case.

    The official repository is:
    https://android-scripting.googlecode.com/hg/

    At time of writing, it's in synch with rjmatthews62

    ReplyDelete
  2. I tried hg pull on rjmatthews62 and the official site and got:
    There is no Mercurial repository here (.hg not found)!
    so I did a clone instead which may not be the best solution to this problem....

    ReplyDelete
  3. ethanthescribe: Robbie Mathews has made so many improvements in such a short time that I thought it better to use his version. I will keep an eye on it to see if this needs changing in the future.
    Peter: I made a mistake (it should have been 'clone' the first time) and I have updated the text. Thanks for pointing it out.

    ReplyDelete
  4. In that case, I did the right thing. Thanks. Although, after cloning (which took some time and several cups of tea) the process created an 'hg' directory as in sl4a/hg and I needed to select this when importing into eclipse as selecting the 'android' directory failed to find any projects.

    ReplyDelete
  5. Thanks John. It worked for me as far as building SL4A -- I didn't do a script.APK.

    I did have some trouble that took figuring. My copy of Eclipse was old and the directory structure of the Android SDK has changed a little so ADB wasn't being found. Eventually I did the updates on Eclipse and got it working.

    Please add to your instructions that if you already have Eclipse and the SDK make sure they are up to date.

    Frank

    ReplyDelete
  6. Frank: Instructions updated regarding your comments, thanks.
    Peter: I got stuck at that point as well. I will try to find out what the problem is.

    ReplyDelete
  7. I created my first apk by following these steps, but the apk failed to run. It crashed immediately after launched. Got any idea?

    My script was written in Lua but not Python.

    ReplyDelete
  8. Thanks for all the work...Now I'll never get outside ;-)

    I followed these posts to the letter and had no problems...It only took 10 minutes to build the sl4a clone over wifi

    ReplyDelete
  9. Having the following error: "ERROR: Unable to open class file /home/derek/workspace/sl4aCloneFiles/hg/android/ScriptingLayerForAndroid/gen/com/googlecode/android_scripting/R.java: No such file or directory".

    I've tried combinations of cleaning/building, changing build path settings, refreshing, restarting eclipse, switching over to Linux from Windows - nothing has solved it yet. Any ideas how to solve this?

    ReplyDelete
  10. ykhuang, sorry for the late reply. I'm afraid I don't know Lua so I can't really help.

    DerekM, Have you checked R.java is actually where it is supposed to be? When you imported the projects did you tick 'copy into workspace'? Try deleting gen and then build all (without cleaning or refreshing first). Eclipse seems to have a few bugs in this area and I'm afraid I'm not an Eclipse expert.

    ReplyDelete
  11. I also have R.java missing in 3 places.


    [2011-06-01 15:57:54 - QuickAction] ERROR: Unable to open class file C:\Android\sl4a\android\QuickAction\gen\net\londatiga\android\R.java: No such file or directory
    [2011-06-01 15:57:54 - ScriptForAndroidTemplate] ERROR: Unable to open class file C:\Android\sl4a\android\ScriptForAndroidTemplate\gen\com\dummy\fooforandroid\R.java: No such file or directory
    [2011-06-01 15:57:58 - ScriptingLayerForAndroid] ERROR: Unable to open class file C:\Android\sl4a\android\ScriptingLayerForAndroid\gen\com\googlecode\android_scripting\R.java: No such file or directory

    ReplyDelete
  12. After much searching I seem to have found the problem. Going into the project properties, Java Build Path, Order and Export, the Android entry was not selected. When selecting it, Eclipse generates the gen directory with R.java in.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. coud be include more pics to illustrate this steps? :)

    and today it's recommended to do it as you said? (not attacking, because you did in february... so... could be something change until today...)

    thanks

    ReplyDelete
  15. Is there a way to add PHP for Android as a library in this setup?

    ReplyDelete
  16. Thanks a lot, JohnK! That's fantastic!

    ReplyDelete
  17. Tested on linux, it work very well. Thank you.

    ReplyDelete
  18. one question i installed and all goes fine :)
    But i wanted that in a virgin terminal without the sl4a how can i set this as an apk so that the user when installing my application (previously copied from the template and exported) don't need to download python?

    ReplyDelete
  19. You seem to be installing the cloned version of SL4A onto the phone (or emulator) - why? Why not simply use the existing SL4A apk?

    ReplyDelete
  20. Hi I am almost there but when running build as ants on Copy of ScriptForAndroidtemplate.xml is get the error build failed ....\scriptinglayer\bin not found how does the scriptinglayerabin find its way into ny workspace. Thanks Steve

    ReplyDelete
  21. I answered my own question by adding the full path to each line in the build.xml file but is there an easier way.

    ReplyDelete
  22. Thanks for the detailed instruction. I could convert my python script to apk, transferred it to the phone as well. But after installing and trying to run I get a pop-up 'Python 2.6.2 is not installed. Do you want to download and install APK for Python 2.6.2'. I installed SL4A or Py4A in my emulator and didn't install them on the phone. Is it necessary for me to install Py4A in my phone to run the generated apk?

    ReplyDelete
  23. This is one of the useful script.I like your blog explanation.This is one of the brilliant post.Thanks for your support.
    Android app developers

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  24. Thank you for the great post! It is very good for a beginner like me, but I have a question:
    Is posible to add an automatic installation of python interpreter when installing my app?? The need of installing python could be a problem for a user who knows nothing about programming languages.

    ReplyDelete
  25. Hello JohnK!

    Thank you for this post, but I have a little problem getting over this step:

    "Now click Project/Build Automatically, then Project/Clean/Clean all Projects/OK. If you get error messages of files missing try Project/Build All without cleaning first. If you still have errors check if any projects have .jar entries in their libs folders which have not yet been added to the build path (right click/BuildPath/add to Build Path if not - but don't put in duplicate entries). Then try Project/Clean/Clean all Projects/OK (and maybe once more if you still have errors). Ignore the numerous warnings."

    Actually, my problem is when I try to "Build All", that option is unavailable to me. Also, I don't have any .jar entries or a "libs" folder.. Also, where should i right click -> buld path/add to build path?

    This step is a bit ambiguous.. could you please explain a little better? Or maybe provide a few images?

    Thanks a lot in advance!

    ReplyDelete
  26. Nevermind, I managed :) I changed the name of the "project.properties" file into "default.properties", right clicked the project and then selected Android Tools -> Fix Project Properties, cleaned and rebuilded.

    ReplyDelete
  27. Though, I have a bit of a question.. can't you run a simple apk without installing Python on the emulator?

    ReplyDelete
  28. For the past few hours I have been struggling with this. Everything went fine until the clean/rebuild step- then the errors didn't go away. I had ~65-70 errors just hanging around & lots about a quickaction.jar that couldn't be found.

    The solution: Since I already had Eclipse installed, my Java Compiler compliance level was at 1.5. It NEEDS to be at least 1.6 to allow overriding certain abstract functions, as these libraries do. Configurable in Project Properties -> Java Compiler -> Configure Workspace Settings... -> Compiler compliance level.

    ReplyDelete
    Replies
    1. I still get this error "The container 'Android Dependencies' references non existing library 'D:\SL4A\hg\android\QuickAction\bin\quickaction.jar' . Any solution to this problem ?

      Delete
  29. This blog is very nice. Thank You for the great post!

    Android Application

    ReplyDelete
  30. I would surely give 10 on 10 for such incredible content.
    check here

    ReplyDelete
  31. Your articles make complete sense out of each topic.click for info

    ReplyDelete
  32. Thank you so much for this post! It was incredibly easy to follow.

    ReplyDelete
  33. why this cloning taking too much time???? does this takes this much time or is it because my internet connection???

    ReplyDelete
  34. How to add new Facade APIs to SL4A ?. I have downloaded SL4A source, compiled and built it in eclipse after adding two hiddent APIs from BluetoothDevice class ( ie, setpin and setpinconfirmation APIs).

    I have wrapped these APIs to add those to SL4A apk. Is this the right way to do ?. Do i have to change anywhereelse ?. BTW, after installing this apk, the new SL4A apk crashes. Any clue ?

    ReplyDelete
  35. This is awesome. It lets you experiment with different scripts and it leaves you from all the android sdk compiling work.

    ReplyDelete