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

Tutorial #59: Implement Accelerometer using Processing for Android

Hey everyone!

Processing is slowly becoming a popular platform for creating Android applications. Although still in beta, it can be used to carry out tasks that we would normally do using an Android device.

In this tutorial, we will learn how to implement an accelerometer using Processing for Android.

Pre-requisites: Processing for Windows (64 bit), Android SDK

Launch the Processing application (.exe) and create a new Sketch named test_accelerometer_android.

Step 1: Installing Android mode

In case you don’t have the Android mode installed, you can do so by clicking on the Add mode option under Mode Manager.

installing_android_mode

Step 2: Write Processing Android

Switch to Android mode and include the following code in your Sketch!


import android.content.Context;                
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

SensorManager sensorManager;       
SensorListener sensorListener;    
Sensor accelerometer;              
float[] accelData;                 

// basic setup
void setup() 
{
  orientation(PORTRAIT);            
  smooth();
  noStroke();
};

void draw() 
{
  background(0);
  
  //get sensor data
  if (accelData != null) {

    fill(255);
    textSize(70);
    textAlign(CENTER, CENTER);
    text("x: " + nf(accelData[0], 1, 2) + "\n" + 
         "y: " + nf(accelData[1], 1, 2) + "\n" + 
         "z: " + nf(accelData[2], 1, 2), 0, 0, width, height);

  }
  else
  {
    text("[ no accelerometer data ]", width/2, height/2);
  }
};

void onResume() 
{
  super.onResume();
  sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
  sensorListener = new SensorListener();
  accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  sensorManager.registerListener(sensorListener, accelerometer, SensorManager.SENSOR_DELAY_GAME);  
};

void onPause() 
{
  sensorManager.unregisterListener(sensorListener);
  super.onPause();
};


class SensorListener implements SensorEventListener 
{
  void onSensorChanged(SensorEvent event) 
  {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) 
    {
      accelData = event.values;
    }
  }
  void onAccuracyChanged(Sensor sensor, int accuracy) 
  {
       //todo 
  }
}

output

Run the Sketch on an Android device by connecting the phone via USB cable to your machine. You should see the accelerometer data being displayed. Alternatively, developers can also use the Ketai library for implementing the same functionality.

Reference: Processing for Android

Source code for this tutorial can be found over here.

Tutorial #1: Android Accelerometer Demo

Hello everyone, today I am going to create an Android application to show how an accelerometer works.

Requirements: Eclipse IDE and Android SDK. I have used Eclipse Helios with target SDK version as Android 2.2 for this tutorial.

Step 1: Create new Android project. I have given my project the name AccelerometerDemo. Let the package name be com.example

Step 2: Create activity class in your project.  I have gone with the default name MainActivity

Now let’s start coding!

1) MainActivity.java

We need to first implement the SensorEventListener for our class:

public class MainActivity extends Activity implements SensorEventListener { }

Now we create an object for SensorManager and Sensor within our MainActivity class. We also declare TextViews and a RelativeLayout used for displaying accelerometer values.

   private SensorManager mSensorManager;
   private Sensor mAccelerometer;
   TextView title,tv,tv1,tv2;
   RelativeLayout layout;

write the onCreate method that defines the starting point of our Activity

   @Override
   public final void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main); //refer layout file code below
      //get the sensor service
      mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
      //get the accelerometer sensor
      mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
      //get layout
      layout = (RelativeLayout)findViewById(R.id.relative);
       //get textviews
      title=(TextView)findViewById(R.id.name);
      tv=(TextView)findViewById(R.id.xval);
      tv1=(TextView)findViewById(R.id.yval);
      tv2=(TextView)findViewById(R.id.zval);
    }

Now we need to override two methods that are associated with SensorEventListener namely onAccuracyChanged and onSensorChanged

  @Override
    public final void onAccuracyChanged(Sensor sensor, int accuracy)
     {
       // Do something here if sensor accuracy changes.
     }
  @Override
   public final void onSensorChanged(SensorEvent event)
     {
      // Many sensors return 3 values, one for each axis.
     float x = event.values[0];
     float y = event.values[1];
     float z = event.values[2];
     //display values using TextView
     title.setText(R.string.app_name);
     tv.setText("X axis" +"\t\t"+x);
     tv1.setText("Y axis" + "\t\t" +y);
     tv2.setText("Z axis" +"\t\t" +z);
     }

After we have done this, it is important to register and unregister the SensorListener in the Activity lifecycle methods onResume and onPause as follows:

   @Override
   protected void onResume()
   {
   super.onResume();
   mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
   }
   @Override
   protected void onPause()
   {
   super.onPause();
   mSensorManager.unregisterListener(this);
   }

2) Layout file: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:id="@+id/relative">

   <TextView 
    android:textSize="30dp" 
    android:id="@+id/name" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />

   <TextView 
    android:textSize="20dp"
    android:layout_below="@+id/name"
    android:id="@+id/xval" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
    
    <TextView 
    android:textSize="20dp"
    android:id="@+id/yval" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/xval"
    />
    
    <TextView 
    android:textSize="20dp"
    android:id="@+id/zval" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:layout_below="@+id/yval" 
    />
  
</RelativeLayout>

Finally, this completes our first tutorial. Run the application and you should see a screen as below:

Complete source code of project can be found over here.