jQM Accelerometer App

Using the accelerometer API in a jQuery Mobile app

🚧

Important Note!

The option of creating new apps with the jQuery Mobile framework was removed but we still support the projects that were created with it earlier.

What are we going to build?

In this tutorial, you’ll learn how to build an app that works with the device’s accelerometer via the PhoneGap Accelerometer API. The app will retrieve accelerometer data with a specified frequency, and display it on the page. The frequency parameter can be changed on the page, and the accelerometer data retrieval can be started or stopped by pressing the button.

The app will look like this:

354

Apache Cordova (PhoneGap)

Apache Cordova (PhoneGap) is automatically included when you create a new project in Appery.io.

Creating New App

Create a new app in the App Builder. From the Apps page, enter an app’s name and click Create. You’ll see a start page.

Creating App UI

  1. Place the Textarea component on the page and rename to acc_info. Clear the Text field.
  2. Place the Button component on the page, and rename it to stop_watch_button. Type “Stop watch” into the Text field.
  3. Next, place the Label component, and type Enter frequency here: into the Text property.
  4. Place the Input component on the page, and name it frequency_input. Type a default frequency value into the Text field. In this case, it’s 500.

Invoking via JavaScript

The following example shows how to work with the accelerometer via JavaScript (without services).

Creating JavaScript File

Move the larger part of the code to a separate JavaScript file.

  1. In the Appery.io App Builder: Create New > JavaScript, enter the name AccelerometerJS, and click Create JavaScript. The new JavaScript file will be listed under the JavaScript folder.
  2. Open the AccelerometerJS file, and add the following code:
var watchID = null;
 
function onSuccess(acceleration) {
    Appery('acc_info').val('Acceleration X: ' + acceleration.x + '\n'
                                       + 'Acceleration Y: ' + acceleration.y + '\n'
                                       + 'Acceleration Z: ' + acceleration.z + '\n'
                                       + 'Timestamp: ' + acceleration.timestamp + '\n');
 
}
 
function onError() {
    Appery('acc_info').val('onError!');
}
  1. Save.

Mapping JavaScript Events

Once the JavaScript file is ready, it’s time to map some events. The Textarea component size is small by default. Make it bigger by adding the following event:

  1. Open the DESIGN tab.
  2. Select startScreen (use breadcrumbs), open the EVENTS tab, and add the following event: startScreen > Load > Run JavaScript.
  3. Add the following JavaScript code:
Appery('acc_info').height(100); //This code makes the textarea bigger
  1. Click Save.

Now we need to launch the acceleration data retrieval:

  1. Add the following event: startScreen > Device ready > Run JavaScript.
  2. Add the following JavaScript code:
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, {'frequency': parseInt(Appery('frequency_input').val())}); //take the frequency value
//from the 'frequency_input' and start to watch for an accelerometer data
  1. Click Save.

Make the start/stop function:

  1. Select stop_watch_button, and add the following event: stop_watch_button > Click > Run JavaScript.
  2. Add the following code:
if (watchID) {
 navigator.accelerometer.clearWatch(watchID);
 watchID = null;
 
 Apperyio('stop_watch_button').text('Start watch'); //change button text to "Start watch"
} else {
 watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, {'frequency': parseInt(Appery('frequency_input').val())}); //create new watchID
 
 Apperyio('stop_watch_button').text('Stop watch'); //change button text to "Stop watch"
}
  1. Click “Save”.

The app is ready for testing. Please recall that since we’re invoking a native component, the app needs to be tested as a hybrid app, or installed on the device.

Wrapping into Service

The accelerometer can also be invoked via a service. Appery.io doesn’t have a predefined Accelerometer component; instead, this example uses a generic service.
Note: Don’t use both methods (Invoking via JavaScript and this one) at the same time.

1.From the App Builder: Create New > Service > Generic (custom JavaScript implementation), enter name AccelerometerService, and click Create Service. The service will be listed under the Services folder.

  1. Open the service, and go to the Request tab. Specify one parameter – frequency.
  2. Go to Response tab and add two parameters – accelerometerData and buttonText.
  3. Go to the Settings tab and click Add custom implementation.
  4. In the dialog box, type AccelerometerImplementation for custom JavaScript implementation and click Create.
  5. Click Open, and you’ll see the default implementation. Replace the default code with the following.
$t.AccelerometerImplementation = $t.createClass(null, {
    
    init: function(requestOptions) {
        this.__requestOptions = $.extend({}, requestOptions);
    },
    
    process: function(settings) {
        if (this.__requestOptions.echo) {
            settings.success(this.__requestOptions.echo);
        } else {
            
            var watchID = localStorage.getItem("watchID"); //get the watchID variable
            var buttonText = "";
            if (watchID) { //check if it already exists or not
                
                navigator.accelerometer.clearWatch(watchID); //if it exists clear and stop watch
                watchID = null;
                localStorage.removeItem("watchID"); //remove this variable from the local storage
                
                buttonText = 'Start watch'; //Text for button
                settings.success({'buttonText':buttonText}); //pass buttonText as parameter in service success method.
                
                
            } else {
                //if it is not exists start watch for accelerometer data
               
                var options = {
                    frequency: parseInt(settings.data.frequency) //get frequency from the request
                }
                    watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); //create new watchID
                
                localStorage.setItem("watchID", watchID); //save new watchID to the local storage
                buttonText = 'Stop watch';
            }
        }
        
        function onSuccess(acceleration) {
            
            var accelerometerData = 'AccelerationX: ' + acceleration.x + '\n'
                +'AccelerationY: ' + acceleration.y + '\n'
                +'AccelerationZ: ' + acceleration.z + '\n'
                +'Timestamp: ' + acceleration.timestamp;
      
                        
            settings.success({'accelerometerData': accelerometerData, 'buttonText':buttonText});
            
        }
        
        //This fires in case of error
        function onError() {
            var accelerometerData = 'Error!';
            settings.success({'accelerometerData': accelerometerData});
        }
        
        settings.complete('success');
        
        
    }
    
});

Mapping Accelerometer Service

  1. Open the DATA tab.
  2. For datasource, select Service > AccelerometerService > Add. The accelerometer service will be added to the page. Name it accelerometer_service.
  3. Define the following mapping action for Before send event, then click Save and return:

1646

  1. Define the Success event mapping, and save.

Launching Service

There are two operations that must be performed before launching the accelerometer service. As with the JavaScript version, the Textarea needs to be a little bigger:

  1. Open the DESIGN tab.
  2. Select startScreen (use breadcrumbs), open the EVENTS tab, and add the following event: startScreen > Load > Run JavaScript.
  3. Add the following JavaScript code:
Appery('acc_info').height(100); //This code makes the textarea bigger
  1. Click Save.

Since the accelerometer implementation (generic service variant) uses local storage to determine when the “watch” must be stopped or started, clearing it upon start-up will guarantee that this check works properly:

  1. Add the following event: startScreen > Device ready > Run JavaScript.
  2. Add the following JavaScript code:
localStorage.clear(); //Remove all items from the localStorage
  1. Click Save.

Launch the accelerometer service when the device is ready:

  1. Add the following event: startScreen > Device ready > Invoke service > accelerometer_service.
  2. Save.

Testing App

Since we’re invoking a native component, the app needs to be tested as a hybrid app, or installed on the device.

Android

Testing on Android is relatively simple, since you can quickly install any app on your device.
To do it, build the Android binary and install it on your device. When the build is completed, you’ll see a QR code. Scanning the QR code will download the app to your phone. You can also email the app to your device.

iOS

Build the iOS binary and install it on your device.

📘

Important Note

Please, note that to export the app for iOS, you will need to upload your distribution certificate and provisioning profile obtained from Apple under the App settings > iOS binary tab.
You can check this document in case you need help with exporting your application for iOS. Here, you will find the document that explains how to manage certificates in Appery.io.