How to use PhoneGap to code and test an app

Learn how to live-preview apps without having to compile and build them

Screen shot 2014-12-10 at 12.33.29

PhoneGap has revolutionised app design and development by allowing HTML, CSS and JavaScript to be used for app development. If we look at the ever-increasing efficiency of JavaScript interpreters on mobile devices, it is getting harder to tell the difference between a native and a hybrid app.

One of the slower areas of the development process was the build. Whether you used the PhoneGap build in the cloud or ran Cordova through a code editor on the desktop, the build process still took a little time to see on the device, meaning a bit of unnecessary waiting around.

But all that has changed since the introduction of the PhoneGap Developer app. Creating PhoneGap apps have been easy but the Developer app really adds something special.
The Developer app sits on the mobile device and allows live pairing to the desktop. As soon as you save in your code editor, the app on the device updates making the testing of native features incredibly fast and efficient.

Get started

The first part of the tutorial is the installation process to get up and running using the PhoneGap desktop and mobile developer app. To work with PhoneGap you actually need to have Node.js installed first. If you haven’t got this, head to and hit the ‘install’ button.

Install Node.js

The right package will download for your computer. Double-click the installer package that has downloaded and follow the on screen prompts to ensure that Node.js has installed. Node.js follows a standard installation procedure so there will be no problem getting this to install on your computer.

Command Line

Now you need to open the Command Line, this is called the ‘Command Line Prompt’ on Windows and ‘Terminal’ on a Mac. Type the code shown into the Command Line, this instigates the npm part of node to download and install PhoneGap to your computer.

001    sudo npm install -g phonegap

Mac first

If this is the first time you have attempted this on a Mac and have never used the ‘CLI’ or ‘Command Line Interface’ before you will be prompted to download and install those tools on your Mac. Follow the onscreen prompts and then redo step 3.

Create the app

It takes a few moments to download the package from PhoneGap so be patient but you will be notified of its success. Now when it’s finished type the code shown below. This tells PhoneGap to create a new PhoneGap application with the name ‘myapp’. You can find this folder on your computer. It is likely to be created in the root folder of your username.

001    phonegap create myapp

Change directories

So this step is probably the easiest to execute as we simply invoke the cd command to change directory into the app directory. We will pause at this point and come back to the terminal in a moment. You will now need to get the PhoneGap Mobile app on your device. It’s available for iOS, Android and Windows phones so get downloading!

001    cd myapp

Install the Mobile app

Obviously you will need to install this on your phone, so search for ‘PhoneGap Developer’ in the device’s store. Once downloaded and installed on the device you can start it up, ready for us to connect across from the desktop application in the terminal window.

Get your IP address

Okay now as we have the PhoneGap Developer app on our device, we need to switch back to the desktop and into terminal. Type the code shown below which will cause phonegap to start serving your application. You will get a response as follows below this ‘listening on’, we will use this on the device in just a moment and the IP address will be for your own computer, rather than the one shown.

001    phonegap serve

Connect the device

In the centre of the app on your device is a server address. You can tap in here and enter the IP address that you were presented with in the previous step. We found that on Android devices you had to actually enter the ‘http://’ but this wasn’t actually necessary on iOS devices, so be prepared in case you have to try both scenarios depending on which operating system you use. Make sure that the ‘:3000’ is included in the address as well, otherwise it
will not work properly.

Demo app

To see the device app working you will see a PhoneGap demo app that shows a green ‘Device is Ready’ message when the app is running. Now we are going to use this to create our app. As the phone and desktop are now connected, every time we save the file the phone will update with the latest changes.

Code Editor

Open the ‘WWW’ folder inside the ‘myapp’ folder. From the tutorial files download drag the images from the ‘start’ folder into the ‘img’ folder. Open the ‘index.html’ page in a code editor, such as ‘Brackets’ and we will start to edit the content on the page to make our own app.

Add the page content

At present the current page displays a PhoneGap image and a flashing message, we don’t actually need any of that, so find in the ‘body’ tag the div with the class ‘app’ and delete everything inside of this div tag. Now add inside the code shown below which will give us the arm of a compass.

001    <div id=”arrow”><img src=”img/arm.png”
width=”30” height=”300” alt=”arm”></div>

Amend the CSS

Open the ‘index.css’ file from the css folder and delete everything from ‘.app’ onwards as we are going to add our own content in here and style it the way we want it to be styled.  We are setting the background image for the ‘app’ div class on the html page.

001    .app {
002        display: block;
003        background-image: url(../img/bg.png);
004        background-repeat: no-repeat;    
005        height:480px;                   
006        width:320px;

Fine tuning

Here we finish off the ‘app’ style by adding a little padding and margin to the top of the div. Notice how we also set the div left and right margin to auto, so that it sits centrally on larger screens. If you saved your document right now, you would see that the PhoneGap app on the device automatically reloads to reflect the changes.

001        text-align:center;
002        padding:60px 0px 0px 0px;     
003         margin:10px auto;  
004    }

CSS rotations

Now we are going to style up the arrow graphic so that we can control it later on by adding the angle to rotate using JavaScript. We are using CSS3 transitions for this, so if you are doing this for Windows phone, just change the prefix to ‘ms’. We are going to check every 0.5 seconds for the compass heading so we set the transition here for the same length.

001        #arrow{
002        -webkit-transition: all 0.5s ease-in-            out;    
003        -webkit-transform-origin: 15px 150px;
004        -webkit-animation-timing-function:             linear;
005        height: 300px;
006        width: 30px;

Position the arrow

Finishing off the CSS for the arrow we make its position relative inside the div with the compass graphic in the background. Because the width of the arm is 30 pixels, we position it left 50% but take off 15 pixels to make it centred. The transform origin point will be in the centre of this arm. Save this CSS file.

001        position: relative;
002        top: 55px;
003        left: 50%;
004        margin-left: -15px;
005        }

Switch to JavaScript

Now we need to open the ‘index.js’ file which is in the ‘JS’ subfolder. This is the code that works the existing app and just sets the message on the screen when PhoneGap detects that the device is ready. We need to remove the code that does this so we can add our own functionality. Find the line ‘receivedEvent: function(id) {‘ and remove all the code between the brackets.

Change direction

Inside the ‘receivedEvent’ function brackets add the code shown below. Here we grab a reference to the arrow in the DOM and when there is success at
retrieving the compass direction, we round-up the heading to a whole number and apply this angle to the arrow in the DOM.

001        var arrow = document.                    getElementById(‘arrow’);
002        function onSuccess(heading) {
003        var dir = Math.round(heading.                magneticHeading);
004 = “rotate(“             + dir + “deg)”;
005        };

Error handler

We need an error handler as PhoneGap requires a success and error outcome for getting any native features. Here we handle this by adding an alert that would tell us what the error was. This is obviously very useful for debugging, but a message display telling you that you are not being able to access the compass
might be better though.

001        function onError(compassError) {
002        alert(‘Compass error: ‘ + compassError.code);
003        };

Set updates

As we will be continually updating the compass we need to set the frequency at which this event takes place. Here we set the frequency to 500 milliseconds so this will update every half a second, which is the same as the transition for the compass. If they’re not the same it doesn’t look right. Finally we call the compass to watch the heading using those options.

001    var options = {
002        frequency: 500
003        };
004    var watchID = navigator.compass. watchHeading(onSuccess, 
onError, options);

Final step

Finally save the JavaScript file and now you should see your device update with your final app. Every half a second the compass will update to show what is on your screen. As you can see, the speed at which your app updates completely negates the need to build your app for the device and all native functionality can be tested on device rather than through a simulator.

Parse error: syntax error, unexpected end of file in /var/www/html/ on line 18