Click here to Skip to main content
15,891,740 members
Articles / Web Development / HTML

Introduction to Android development with Cordova and Web Starter Kit

Rate me:
Please Sign up or sign in to vote.
4.71/5 (13 votes)
22 Sep 2014CPOL7 min read 24.9K   21   10
How to get started with Cordova and the Web Starter Kit framework when developing apps for Android (which you can then expand to include other targets like iOS, Windows Phone and Windows8 Store Apps)

Introduction

Everyone wants to make mobile apps these days, and why not? There are more mobile devices around the world than any other user device. Android is particularly popular, but why not get started with a well-known foundation for cross-platform applications? Development for Android is definitely easier than for the other platforms (particularly when considering deployment and device / virtual device testing), so this tutorial aims at Android, but do bear in mind that once you're up and running with these instructions, you're only a step away from targeting other platforms. And by "a step", I literally mean that it can be as simple as one command (which is all I needed to to do get my application compiling for Windows Phone).

This article references a GitHub repository which is currently quite bare -- it's mostly documentation. The aim is to expand the project to provide helpers for the steps outlined below. Also, these steps were used to produce the application you can currently find in the Play Store: Hackendot (https://play.google.com/store/apps/details?id=com.hackendot). Please note that the app is totally free, so feel free to try it out. Although there is a donate button, you are under no obligation whatsoever to donate, so please don't think that I'm trying to fish here -- it's merely a reference app to show you that what I've done actually works.

Before we get going though, some disclaimers and clarifications:

  1. I'm not affiliated with any of the projects I'm using below (although I do currently have a GitHub project up to help with this process and I'm hoping that might one day have more than just documentation in it; that it would also contain some utilities to streamline this process)
  2. I am, in no way, in any position to stand to gain from you using this process or these tools. This is just something which has worked for me (and some people I've helped with this). YMMV, so if you hit a snag, please rather post a question than have a meltdown (:
  3. You're going to need to type a lot and read what your tools say to you. Whilst this is a beginner tutorial, I don't think that's unreasonable -- if typing is something you're afraid of, perhaps programming isn't for you ^_^
  4. This process is currently still evolving. However, I believe there's enough to get going with a tutorial!
  5. I make no claims as to the quality or reliability of the outcome. I'm just providing a tutorial on how to use quite a few freely available tools to build Android applications using HTML5 and Javascript. I sincerely hope that this information will be useful, however.

Background

Web Starter Kit (https://developers.google.com/web/starter-kit/)is a framework developed by google to assist with the creation of websites which have a responsive design and a small footprint. I chose it as a base for this tutorial because:

  • It's small
  • It's fast
  • It's actively developed and maintained
  • It felt quite natural as a mobile application (web or app)
  • Provides a really rapid development cycle with the "gulp serve" command: when running, your changes are reflected in a browser as you make them so you can immediately see what you've done and debug errors without waiting for deployment to a device or virtual device.
  • Minifies all of your HTML, CSS and Javascript for the smallest, fastest app you can get.

Cordova (http://cordova.apache.org/) is a framework for deploying HTML5/Javascript applications to multiple targets including iOS, Android and Windows Phone. Note, however, that to build for iOS, you'll need a Mac as a build server. It's nice to use as a basis for developing Android apps because:

  • You develop with HTML5 and Javascript -- tools most of us already enjoy
  • You can target multiple mobile platforms, though Android is by far the easiest to get going with
  • It's totally free! Other paid producs use Cordova as their basis (eg PhoneGap). There are other free frameworks which use Cordova too -- check out Ionic if you're interested (though Ionic has more emphasis on iPhone than anything else and doesn't have the advantages of Web Starter Kit)

The source for this information is continually evolving at https://github.com/fluffynuts/whisk . There are also some files there to help you get going (such as an already set-up gulpfile.js, package.json and .jshintrc. At time of writing, I'm also working on instructions (and modifications to the gulfile) for using karma with your code to run tests. But for a beginner tutorial, I think there's enough below... for now!

Using the information...

(pre-amble: when you see a line prefixed with "> ", it's a command you can run from cmd.exe.

to run it, obviously strip out the leading "> ". So if you see:

> run_stuff.bat


You would open a console and type:

run_stuff.bat

 

and press enter.

Useful links:
1) Cordova CLI reference: http://cordova.apache.org/docs/en/3.5.0//guide_cli_index.md.html#The%20Command-Line%20Interface
2) Getting started with Web Starter Kit: https://developers.google.com/web/fundamentals/tools/setup/setup_kit


Pre-requisites for the entire process:

System tool pre-requisites (please run with an elevated console for best results)

1) Package management for some useful tools: go get Chocolatey from https://chocolatey.org/
    (or, just run this in a console):

> @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

 

This is the same instruction you'd get from here: http://chocolatey.org/, so if you don't want to trust a copy-and-paste from me (and I don't blame you), then head on over there for the original commandline (:

2) you need some form of the commandline unzip to do a later step as prescribed, so if

> where unzip

    produces an error like "could not find files for the given pattern(s)", do

> choco install devbox-unzip


    or better, but takes much longer: get gnuwin, because it's useful

 

> choco install gnuwin


    - note that gnuwin takes quite a while to install; if, for some reason, you interrupt it
        and want to pick up later, you can do:

> choco install -force gnuwin


3) you're going to spend some time in a console. You might as well get ConEmu:

> choco install conemu


    - and start using it, of course! ConEmu is prettier, properly resizable and does tabbing.
4) you need git for this

> where git

    should print out a path. If not, do

> choco install git


    or go install SourceTree (https://www.atlassian.com/software/sourcetree/overview), set up and allow it to download git and add
      that git to your path


Web Starter Kit pre-requisites:

1) simple instructions to install pre-requisites (as per https://developers.google.com/web/fundamentals/tools/setup/setup_kit)
    - install node.js

> choco install nodejs.install


    - install ruby -- ONLY IF YOU DON'T HAVE IT (otherwise you'll lose your existing gems)

> choco install ruby1.9


    - install sass:

> gem install sass


    - install gulp

> npm install -g gulp


    - for android, let's get the SDK now (you can carry on with the rest as
      this comes down)

> choco install android-sdk


    - this puts the Android SDK under %LOCALAPPDATA%\Android\android-sdk
        - in there, you can find the SDK Manager and the AVD Manager
        - you will need to add the tools folder to your path! Don't use setx for this
        as it does the WRONG thing if your PATH variable is longer than 1024 chars ):
        - you will also need platform-tools in your path (again, DON'T USE SETX)
            - so you should have the following in your path:

%LOCALAPPDATA%\Android\android-sdk\tools

%LOCALAPPDATA%\Android\android-sdk\platform-tools


        - when the Android SDK is in your path, you should be able to run:

> where android

        and actually get a path back, not an error


    - install cordova

> npm install -g cordova

 

Time to start on an app!

Part 1: Let's create a basic app shell with Web Starter Kit

1) clone the web starter kit somewhere

> git clone <a href="https://github.com/google/web-starter-kit.git">https://github.com/google/web-starter-kit.git </a>C:\path\To\WebStarterKit

3) Create a copy for your project

> mkdir C:\Path\To\Project<br />
> cd C:\path\To\WebStarterKit<br />
> git archive master --format zip > %TEMP%\wsk.zip

   - unzip the file it created at <some temp location> into your source root
> cd C:\Path\To\Project<br />
> mkdir source<br />
> cd source<br />
> unzip %TEMP%\wsk.zip

4) install local dependencies for your project:

> cd C:\Path\To\Project\source<br />
> npm install

        - note that, if you get oddness at some point, first try:
> npm cache clean<br />
> npm update

5) Create the cordova app. In the root of your source folder do:

> mkdir dist<br />
<pre>> cordova create dist com.yourapp.id YourAppName

6) modify gulpfile.js to use the www folder in the created cordova folder. You can use the gulpfile.js at https://github.com/fluffynuts/whisk/blob/master/docs/gulpfile.js to get going!

    wherever it would have used the folder 'dist'. If you used the dist folder
    above, change all references to 'dist' to be 'dist/www'
    NB: especially important is to make sure that the 'clean' task looks at dist/www

7) Because of how Cordova and Web Starter Kit do things (and then interact), we need to
    make some modifications:
    a) rename app\scripts\main.js app\scripts\999_main.js
        - add this to the end of the file, just before the last line (

})();

            window.closeMenu = closeMenu;
            window.toggleMenu = toggleMenu;
            To save you some time, you can get a 999>main.js from https://github.com/fluffynuts/whisk/blob/master/docs/app/scripts/999_main.js
        - this exports the menu interactions into the global namespace. My shell
            998_app.js uses that. You can get the shell app.js from https://github.com/fluffynuts/whisk/blob/master/docs/app/scripts/998_app.js and use that as a starting point for your app.
    b) copy cordova.js from https://github.com/fluffynuts/whisk/blob/master/docs/app/cordova.js into your app folder
       - this is a shim which fakes out the parts of cordova I've used so far
         and ensures that the real cordova.js is loaded at runtime
    c) copy in the libs from https://github.com/fluffynuts/whisk/tree/master/docs/app/lib (jquery especially, jquery.pullToRefresh if you want that functionality in your app)
    d) if you want to store and retrieve user prefs, copy in 002_PrefsHelper.js (https://github.com/fluffynuts/whisk/blob/master/docs/app/scripts/002_PrefsHelper.js) and
       do:
        > cordova plugin add me.apla.cordova.app-preferences
    e) if you want to open links in the user's browser, copy in 001_WebHelper.js (https://github.com/fluffynuts/whisk/blob/master/docs/app/scripts/001_WebHelper.js)
       and do:
       > cordova plugin add https://github.com/Initsogar/cordova-webintent
       (there's more to it than that, but we'll come back to that)
    f) copy 998_app.js (https://github.com/fluffynuts/whisk/blob/master/docs/app/scripts/998_app.js) into your scripts folder. This is a shell app to get you going.
    g) modify index.html to reference these scripts
        
    h) modify index.html to take out google analytics
    i) remove basic.html
    j) copy in .jshintrc to allow double-quotes for strings in your javascript

8) build your app with:
    > gulp
    - if you get an error about an invalid option -strip, modify your
      gulpfile.js in the 'images' task, commenting out the pipe with
      $.imagemin in it -- for some reason, old versions of optipng
      don't support the -strip option but imagemin expects it to.

      Your images task could probably look like:

        // Optimize Images
        gulp.task('images', function () {
        return gulp.src('app/images/**/*')
            //.pipe($.cache($.imagemin({
            //  progressive: true,
            //  interlaced: true
            //})))
            .pipe(gulp.dest(distFolder('images')))
            .pipe($.size({title: 'images'}));
        });


9) test that it is built with:
    > gulp serve
    you can press ctrl-c to stop this

At the moment, you have a responsive web app... We can take this further!

Part 2: let's turn this into an android app

1) you're going to need an emulator and SDK libraries for Android:
    > android sdk
    - select everything from the latest SDK that you see there. Avoid SDKs
      with the "W" affix -- they're for Android Wear. Also, avoid previews
      for now; as of the time of writing, you'll probably want 4.4.2 and
      all of the associated stuff (level 19.1)
    > android avd
    - create a virtual machine using the sdk you downloaded with device specs
      that you like, for example:
        AVD Name: 4.4.2_x86
        Device: Nexus 7 (2012) (7", 800x1280)
        Target: Android 4.4.2 - API Level 19
        CPU/ABI: Intel Atom (x86)
        Keyboard: [x] Hardware keyboard present
        Skin: Dynamic
        Front Camera: None
        Back Camera: None
        Memory Options: RAM: 1024  VM Heap: 32
        Interal Storage: 666 MiB
        SD Card: None confgured
        Emulation Options: [x] Snapshot [ ] Use Host GPU
    > emulation is MUCH faster if you use HAXM (https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager)
        - if you have Hyper-V running, though, you need to disable it (as Hyper-V
            plays nicely with NO-ONE)
            > bcdedit /set hypervisorlaunchtype off
            - more info here:
            http://www.hanselman.com/blog/SwitchEasilyBetweenVirtualBoxAndHyperVWithABCDEditBootEntryInWindows81.aspx
        

2) install java
    > java -version
        should ouput version information, like 1.7.0_something
    if you get "command not found" or something like "not recognised as an internal
    or external command", you need to actually install java
    > choco install javaruntime
    - java isn't enough -- you need the jdk :/
    > choco install java.jdk

2) install ant
   > choco install ant
   check that it's in your path:
   > where ant

3) let's tell the cordova app to support Android:
   > cd dist
   > cordova platform add android

4) Time to build:
    > cordova build
    > cordova emulate android --target=4.4.2_x86

    - note that your first run of the emulator will take a /very/ long
      time to boot up. It gets better later (:
    - you will have to find and run your app in the emulator


Development cycle:


The above should have gotten you a simple app. However, we still need to tweak
stuff to get Cordova to play nicely.

1) you need to include cordova.js in your index.html. There's a shim cordova.js in the
    folder you got this text file from. It emulates the deviceready event and brings
    in the real cordova when you're on a device. At some point later, it may be
    fleshed out with more cordova shimming.
    - My webHelper script allows for opening urls in the OS native browser
    - My PrefsHelper.js helps with using the prefs plugin when devving in the browser
        by shimming out the required functions
    - Note that my cordova.js REQUIRES jquery, so you should link that in too. And
        if you want to use my pullToRefresh jquery plugin, you'll need that. The final
        scripts listing you would need (to start with) would be:

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="lib/jquery.js"></script>
    <script type="text/javascript" src="lib/jquery.pullToRefresh.js"></script>
    <script type="text/javascript" src="scripts/001_WebHelper.js"></script>
    <script type="text/javascript" src="scripts/002_PrefsHelper.js"></script>
    <script type="text/javascript" src="scripts/998_app.js"></script>
    <script type="text/javascript" src="scripts/999_main.js"></script>
                 


Notes:
Remote debugging via Chrome appears to require the adb daemon to be running, which
you can get with:
> adb devices

the "menubutton" event in Cordova is unreliable: https://issues.apache.org/jira/browse/CB-1574 This is normally fired when using the hardware menu button, if supported on your device (eg Galaxy S1-S3).

If you're going to do cross-domain requests (typically, if you're loading anything using $.get,
$.post or similar), you're going to run into an issue:
Your app will be able to make the requests because it would be quite useless to not be able to.
However, regular web browser security prohibits this kind of behaviour, so if you're going to
use Chrome to dev your site (with gulp serve), you'll want this extension:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en

Opening web links in external windows:
1) you want to convert / create links that use window.open for testing
2) you want https://github.com/Initsogar/cordova-webintent for sharing intents on android
3) -- not sure about other platforms

Setting up the application icon:

 

(http://cordova.apache.org/docs/en/3.2.0/config_ref_images.md.html)
Images need to be under dist/www/res/icons/android (for android) and similar for other platforms. However, dist/www is cleared up by gulp. So let's put that alongside dist (ie alongside app as well): create the folder
 + res/icons/android

 

in your source folder and put icons in there and let's get gulp to copy that in when it's done
    - see gulp targets 'push' and 'cordova-build-android' from the linked gulpfile.js above
    - note that for initial testing, I'm just targeting android here, but it's trivial to add Windows Phone 8 support and Windows8 Store support isn't too far off -- mainly needs you to tweak the images below to fit the requirements of the store.

Also:
https://gist.github.com/LinusU/7515016
- also need to mention it in config.xml
http://stackoverflow.com/questions/17820492/how-to-add-app-icon-within-phonegap-projects
    - cordova 3.5.0 is supposed to respect the config.xml element 'icon' for all
       platforms, all targets;
        - however, of course, it's not that simple. On Android, the default icon
            is set up but all of the arb resolutions aren't. So you want lines like:
    <icon src="www/res/icons/android/icon-36-ldpi.png" />
    <icon src="www/res/icons/android/icon-36-ldpi.png" platform="android" density="ldpi" />
    <icon src="www/res/icons/android/icon-48-mdpi.png" platform="android" density="mdpi" />
    <icon src="www/res/icons/android/icon-72-hdpi.png" platform="android" density="hdpi" />
    <icon src="www/res/icons/android/icon-96-xhdpi.png" platform="android" density="xhdpi" />

 

Points of Interest

  • Once the project is up and running, development is quite quick. I suggest working in the browser until you're happy with a feature-set then deploy to a device for final testing. I've sometimes found little things which work fine in a browser but not quite as well on an actual device, so this "last mile" of testing is quite important.
  • As of Web Starter Kit 0.5.0, all CSS work is done via Sass (.scss files), which is excellent! I heartily suggest learning more about Sass
  • I'm currently working on steps to get Karma into the build and run system so you can write tests for your Javascript and run whenever you build or change a file. I'm quite close to having slick instructions and an updated gulpfile.js -- stay tuned!

History

2014-09-22: initial article.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Codeo
South Africa South Africa
Problem solver, sometimes with code.

Comments and Discussions

 
GeneralMy vote of 2 Pin
TenMinJoe19-Nov-14 0:13
TenMinJoe19-Nov-14 0:13 
GeneralRe: My vote of 2 Pin
Davyd McColl19-Nov-14 1:32
Davyd McColl19-Nov-14 1:32 
GeneralRe: My vote of 2 Pin
TenMinJoe19-Nov-14 2:02
TenMinJoe19-Nov-14 2:02 
GeneralRe: My vote of 2 Pin
Davyd McColl19-Nov-14 2:16
Davyd McColl19-Nov-14 2:16 
GeneralRe: My vote of 2 Pin
Davyd McColl19-Nov-14 2:21
Davyd McColl19-Nov-14 2:21 
GeneralRe: My vote of 2 Pin
TenMinJoe19-Nov-14 2:34
TenMinJoe19-Nov-14 2:34 
GeneralRe: My vote of 2 Pin
Davyd McColl19-Nov-14 2:49
Davyd McColl19-Nov-14 2:49 
GeneralRe: My vote of 2 Pin
TenMinJoe19-Nov-14 2:57
TenMinJoe19-Nov-14 2:57 
GeneralRe: My vote of 2 Pin
Davyd McColl19-Nov-14 3:00
Davyd McColl19-Nov-14 3:00 
GeneralThanks for entering! Pin
Kevin Priddle25-Sep-14 4:44
professionalKevin Priddle25-Sep-14 4:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.