Tutorial #72: Implement accelerometer in PhoneGap

Like Android and other existing mobile operating systems, Phonegap too provides the Accelerometer API to capture device motion in the x, y and z directions. An accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation. The accelerometer can detect 3D movement along the co-ordinate axes.

In this tutorial, we will learn how to implement an accelerometer sensor using the PhoneGap framework. In this case, our target platform would be Android. You can download the latest version of PhoneGap from over here.

Pre-requisites: Eclipse IDE

Create new Android application project called PhoneGapAccelerometerDemo with package name com.example and add the following code within the MainActivity class!

MainActivity.java

package com.example;

import android.os.Bundle;
import android.util.Log;
import org.apache.cordova.*;

public class MainActivity extends DroidGap {
	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("PhoneGapAccelerometerApp", "onCreate: Entered method.");
		super.loadUrl("file:///android_asset/www/index.html");
	}
}

Next, let’s create an index.html file for PhoneGap to load. It will be used to display the accelerometer values on screen.

assets/www/index.html

<html>
<head> 

<script src="scripts/cordova.js" type="text/javascript"></script>
<script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="scripts/jquery.mobile-1.0.1.min.js" type="text/javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/jquery.mobile-1.0.1.min.css" />
<script type="text/javascript">
 
    var sensorAcc = null;
 
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {
        var options = { frequency: 80 };

        sensorAcc = navigator.accelerometer.watchAcceleration(accelerometerSuccess, accelerometerError, options);
    }
	
	function accelerometerError() {
        alert('Failed to load accelerometer!');
    }
	
	function accelerometerSuccess(acceleration) {        
        var str = 'Acceleration X: ' + acceleration.x + '<br />' +
                  'Acceleration Y: ' + acceleration.y + '<br />' +
                  'Acceleration Z: ' + acceleration.z + '<br />';
        $('div.result').html(str); 
    }
	
</script>
</head>
<body>

<div class='result'> </div>

</body>
</html>

res/xml/config.xml

<?xml version="1.0" encoding="utf-8"?>
<cordova>

    <access origin="http://127.0.0.1*"/> <!-- allow local pages -->

    <content src="index.html" />

    <log level="DEBUG"/>
    <preference name="useBrowserHistory" value="true" />
    <preference name="exit-on-suspend" value="false" />
    
  <plugins>
    <plugin name="App" value="org.apache.cordova.App"/>
    <plugin name="Geolocation" value="org.apache.cordova.GeoBroker"/>
    <plugin name="Device" value="org.apache.cordova.Device"/>
    <plugin name="Accelerometer" value="org.apache.cordova.AccelListener"/>
    <plugin name="Compass" value="org.apache.cordova.CompassListener"/>
    <plugin name="Media" value="org.apache.cordova.AudioHandler"/>
    <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/>
    <plugin name="Contacts" value="org.apache.cordova.ContactManager"/>
    <plugin name="File" value="org.apache.cordova.FileUtils"/>
    <plugin name="Notification" value="org.apache.cordova.Notification"/>
    <plugin name="Storage" value="org.apache.cordova.Storage"/>
    <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/>
    <plugin name="Capture" value="org.apache.cordova.Capture"/>
    <plugin name="Battery" value="org.apache.cordova.BatteryListener"/>
    <plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
    <plugin name="Echo" value="org.apache.cordova.Echo" />
    <plugin name="Globalization" value="org.apache.cordova.Globalization"/>
    <plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser"/>
	<plugin name="SpeechRecognizer" value="com.example.SpeechRecognizer"/>   
  </plugins>

</cordova>


Do not forget to add the cordova.js and cordova.jar files to your project. As seen from the above code, the accelerometer.watchAcceleration gets the device’s current acceleration at a regular interval. Each time the Acceleration is retrieved, the accelerometerSuccess callback function is executed. You need to specify the interval in milliseconds via the frequency parameter in the acceleratorOptions object.

Finally, save and run the application on an Android device and you should see the following output!

phonegap_accelerometer

Source code for this tutorial can be found over here

Implement notification alerts using PhoneGap!

Hey everyone!

In my previous post, I spoke about the PhoneGap framework and how one can start using it for Android. In this post I will implement a basic Notification alert using the PhoneGap API.

Step 1: Create config.xml

You need to create a config.xml file under the assets/www folder and include the following content!

<?xml version="1.0" encoding="UTF-8"?>

<feature name="Notification">
  <param name="wp-package" value="Notification"/>
</feature>

Step 2: Make changes to existing HTML page

Now, let’s modify our previous HTML page to include a button and the PhoneGap notification alert.

<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>

<script>

function showAlert(){

navigator.notification.alert("This is a test alert!", test , "New Alert" , "OK")

}


function test(){
   //do something
}

</script>
</head>
<body>
<h1>Test PhoneGap</h1>

<input type="button" onclick="showAlert();" id="btn" value="Click me to display alert"/>

</body>
</html>

Syntax for notification.alert method

navigator.notification.alert(message, alertCallback, [title], [buttonName]) 

where,

message: Dialog message (String)
alertCallback: Callback to invoke when alert dialog is dismissed. (Function)
title: Dialog title (String) (Optional, Default: “Alert”)
buttonName: Button name (String) (Optional, Default: “OK”)

When you click the button, you should see the following output!

phonegap_navigation_alert

Reference: PhoneGap Notification

Getting started with PhoneGap!

Hello guys,

In recent times, the number of cross platform mobile applications is gradually increasing with more and more developers trying to run their applications on the various mobile platforms. In these situations, PhoneGap is one of the popular solutions out there allowing developers to create applications using web technologies like HTML, CSS and JavaScript. It is free and open source and can be installed from over here.

Through this post, we will learn how to start using PhoneGap for Android!

Pre-requisites: Eclipse IDE, PhoneGap version 2.7.0

Step 1: Create a new Android Project

Open Eclipse IDE and create a new Android Application project named TestPhoneGap with package name com.example

Step 2: Add PhoneGap files

Create a new folder called www under the assets folder and add the cordova javascript file (cordova-2.7.0.js) inside it. Also, add the cordova-2.7.0 jar file inside the libs folder of your Android project.

Step 3: Create HTML page

Create a new HTML page named index.html under assets/www folder with a simple test message!

Step 4: Modify Activity class and AndroidManifest files

Finally, you need to make changes to your MainActivity class and the AndroidManifest.xml as follows!

MainActivity.java

package com.example;

import org.apache.cordova.Config;
import org.apache.cordova.DroidGap;
import android.os.Bundle;

public class MainActivity extends DroidGap {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		super.loadUrl(Config.getStartUrl());

	}	
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0">
   
    <supports-screens android:largeScreens="true"
	android:normalScreens="true"
	android:smallScreens="true"
	android:resizeable="true"
	android:anyDensity="true"/>
      
    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="17"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Save all files and make sure no errors are present. When you run the application, you should see the following output!

test_phonegap