Saturday, May 24, 2014

Accelerometer Basic Example - Detect Phone Shake Motion

In this example detecting Accelerometer Motion, when Accelerometer force value cross thersold showing an alert for motion detected.

Use:

  1. You can use this example in games based on Accelerometer Motion (Phone Tilt).
  2. You can use this example for battary consumption when using GPS Calls. Combine Screen Wake Sleep Example with this example to consume less battary when calling GPS calls.Later We will give combined example to consume less battery.


Note:


Check this example in real device.

Project Structure:




File : src/AccelerometerListener.java

Create Interface AccelerometerListener and create method onShake, we will override this function in main activity file and listener will call this method when motion detected.

  1. public interface AccelerometerListener {
  2. public void onAccelerationChanged(float x, float y, float z);
  3. public void onShake(float force);
  4. }

File : src/MainAccelerometer.java

This is the maain file aand Start Accelerometer listening on Activity onResume and stop Accelerometer listening on Activity onStop and onDestroy

  1. package com.androidexample.accelerometerexample;
  2.  
  3. import android.os.Bundle;
  4. import android.app.Activity;
  5. import android.util.Log;
  6. import android.widget.Toast;
  7.  
  8. public class MainAccelerometer extends Activity implements AccelerometerListener{
  9.  
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.accelerometer_example_main);
  14. // Check onResume Method to start accelerometer listener
  15. }
  16. public void onAccelerationChanged(float x, float y, float z) {
  17. // TODO Auto-generated method stub
  18. }
  19.  
  20. public void onShake(float force) {
  21. // Do your stuff here
  22. // Called when Motion Detected
  23. Toast.makeText(getBaseContext(), "Motion detected",
  24. Toast.LENGTH_SHORT).show();
  25. }
  26.  
  27. @Override
  28. public void onResume() {
  29. super.onResume();
  30. Toast.makeText(getBaseContext(), "onResume Accelerometer Started",
  31. Toast.LENGTH_SHORT).show();
  32. //Check device supported Accelerometer senssor or not
  33. if (AccelerometerManager.isSupported(this)) {
  34. //Start Accelerometer Listening
  35. AccelerometerManager.startListening(this);
  36. }
  37. }
  38. @Override
  39. public void onStop() {
  40. super.onStop();
  41. //Check device supported Accelerometer senssor or not
  42. if (AccelerometerManager.isListening()) {
  43. //Start Accelerometer Listening
  44. AccelerometerManager.stopListening();
  45. Toast.makeText(getBaseContext(), "onStop Accelerometer Stoped",
  46. Toast.LENGTH_SHORT).show();
  47. }
  48. }
  49. @Override
  50. public void onDestroy() {
  51. super.onDestroy();
  52. Log.i("Sensor", "Service distroy");
  53. //Check device supported Accelerometer senssor or not
  54. if (AccelerometerManager.isListening()) {
  55. //Start Accelerometer Listening
  56. AccelerometerManager.stopListening();
  57. Toast.makeText(getBaseContext(), "onDestroy Accelerometer Stoped",
  58. Toast.LENGTH_SHORT).show();
  59. }
  60. }
  61.  
  62. }

File : src/AccelerometerManager.java

In this class define functions to start acclerometer sensor related functions like.. Check for acclerometer sensor,start acclerometer sensor,stop acclerometer sensor.

  1. import java.util.List;
  2. import android.content.Context;
  3. import android.hardware.Sensor;
  4. import android.hardware.SensorEvent;
  5. import android.hardware.SensorEventListener;
  6. import android.hardware.SensorManager;
  7. import android.widget.Toast;
  8.  
  9. public class AccelerometerManager {
  10. private static Context aContext=null;
  11. /** Accuracy configuration */
  12. private static float threshold = 15.0f;
  13. private static int interval = 200;
  14. private static Sensor sensor;
  15. private static SensorManager sensorManager;
  16. // you could use an OrientationListener array instead
  17. // if you plans to use more than one listener
  18. private static AccelerometerListener listener;
  19. /** indicates whether or not Accelerometer Sensor is supported */
  20. private static Boolean supported;
  21. /** indicates whether or not Accelerometer Sensor is running */
  22. private static boolean running = false;
  23. /**
  24. * Returns true if the manager is listening to orientation changes
  25. */
  26. public static boolean isListening() {
  27. return running;
  28. }
  29. /**
  30. * Unregisters listeners
  31. */
  32. public static void stopListening() {
  33. running = false;
  34. try {
  35. if (sensorManager != null && sensorEventListener != null) {
  36. sensorManager.unregisterListener(sensorEventListener);
  37. }
  38. } catch (Exception e) {}
  39. }
  40. /**
  41. * Returns true if at least one Accelerometer sensor is available
  42. */
  43. public static boolean isSupported(Context context) {
  44. aContext = context;
  45. if (supported == null) {
  46. if (aContext != null) {
  47. sensorManager = (SensorManager) aContext.
  48. getSystemService(Context.SENSOR_SERVICE);
  49. // Get all sensors in device
  50. List sensors = sensorManager.getSensorList(
  51. Sensor.TYPE_ACCELEROMETER);
  52. supported = new Boolean(sensors.size() > 0);
  53. } else {
  54. supported = Boolean.FALSE;
  55. }
  56. }
  57. return supported;
  58. }
  59. /**
  60. * Configure the listener for shaking
  61. * @param threshold
  62. * minimum acceleration variation for considering shaking
  63. * @param interval
  64. * minimum interval between to shake events
  65. */
  66. public static void configure(int threshold, int interval) {
  67. AccelerometerManager.threshold = threshold;
  68. AccelerometerManager.interval = interval;
  69. }
  70. /**
  71. * Registers a listener and start listening
  72. * @param accelerometerListener
  73. * callback for accelerometer events
  74. */
  75. public static void startListening( AccelerometerListener accelerometerListener )
  76. {
  77. sensorManager = (SensorManager) aContext.
  78. getSystemService(Context.SENSOR_SERVICE);
  79. // Take all sensors in device
  80. List sensors = sensorManager.getSensorList(
  81. Sensor.TYPE_ACCELEROMETER);
  82. if (sensors.size() > 0) {
  83. sensor = sensors.get(0);
  84. // Register Accelerometer Listener
  85. running = sensorManager.registerListener(
  86. sensorEventListener, sensor,
  87. SensorManager.SENSOR_DELAY_GAME);
  88. listener = accelerometerListener;
  89. }
  90. }
  91. /**
  92. * Configures threshold and interval
  93. * And registers a listener and start listening
  94. * @param accelerometerListener
  95. * callback for accelerometer events
  96. * @param threshold
  97. * minimum acceleration variation for considering shaking
  98. * @param interval
  99. * minimum interval between to shake events
  100. */
  101. public static void startListening(
  102. AccelerometerListener accelerometerListener,
  103. int threshold, int interval) {
  104. configure(threshold, interval);
  105. startListening(accelerometerListener);
  106. }
  107. /**
  108. * The listener that listen to events from the accelerometer listener
  109. */
  110. private static SensorEventListener sensorEventListener =
  111. new SensorEventListener() {
  112. private long now = 0;
  113. private long timeDiff = 0;
  114. private long lastUpdate = 0;
  115. private long lastShake = 0;
  116. private float x = 0;
  117. private float y = 0;
  118. private float z = 0;
  119. private float lastX = 0;
  120. private float lastY = 0;
  121. private float lastZ = 0;
  122. private float force = 0;
  123. public void onAccuracyChanged(Sensor sensor, int accuracy) {}
  124. public void onSensorChanged(SensorEvent event) {
  125. // use the event timestamp as reference
  126. // so the manager precision won't depends
  127. // on the AccelerometerListener implementation
  128. // processing time
  129. now = event.timestamp;
  130. x = event.values[0];
  131. y = event.values[1];
  132. z = event.values[2];
  133. // if not interesting in shake events
  134. // just remove the whole if then else block
  135. if (lastUpdate == 0) {
  136. lastUpdate = now;
  137. lastShake = now;
  138. lastX = x;
  139. lastY = y;
  140. lastZ = z;
  141. Toast.makeText(aContext,"No Motion detected",
  142. Toast.LENGTH_SHORT).show();
  143. } else {
  144. timeDiff = now - lastUpdate;
  145. if (timeDiff > 0) {
  146. /*force = Math.abs(x + y + z - lastX - lastY - lastZ)
  147. / timeDiff;*/
  148. force = Math.abs(x + y + z - lastX - lastY - lastZ);
  149. if (Float.compare(force, threshold) >0 ) {
  150. //Toast.makeText(Accelerometer.getContext(),
  151. //(now-lastShake)+" >= "+interval, 1000).show();
  152. if (now - lastShake >= interval) {
  153. // trigger shake event
  154. listener.onShake(force);
  155. }
  156. else
  157. {
  158. Toast.makeText(aContext,"No Motion detected",
  159. Toast.LENGTH_SHORT).show();
  160. }
  161. lastShake = now;
  162. }
  163. lastX = x;
  164. lastY = y;
  165. lastZ = z;
  166. lastUpdate = now;
  167. }
  168. else
  169. {
  170. Toast.makeText(aContext,"No Motion detected", Toast.LENGTH_SHORT).show();
  171. }
  172. }
  173. // trigger change event
  174. listener.onAccelerationChanged(x, y, z);
  175. }
  176. };
  177. }

File : AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidexample.accelerometerexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidexample.accelerometerexample.MainAccelerometer"
            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>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
</manifest>

File : accelerometer_example_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"
    tools:context=".MainAccelerometer" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Shake / Tilt Your Phone To Get Accelerometer Motion Alerts" />

</RelativeLayout>

No comments:

Post a Comment