SlideShare a Scribd company logo
1 of 12
Android Application Development Training Tutorial




                      For more info visit

                   http://www.zybotech.in




        A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Android Accelerometer Sensor tutorial
Android supports a wide variety of sensors that can be used by applications to capture informations about the
phone’s environment.

In this tutorial, we’ll see how to use the accelerometer sensor in an application in order to capture acceleration
change events. We’ll use these events to build a custom listener that will trigger others events such as shake
events :

package net.androgames.bolg.sample.accelerometer;

public interface AccelerometerListener {

          public void onAccelerationChanged(float x, float y, float z);

          public void onShake(float force);

}

An instance of the SensorManager is required in order to retrieve informations about the supported sensors. No
permission is required to access the sensor service. It is then possible to retrieve the list of available sensors of a
certain type. For an accelerometer sensor, the type to use is given by the Sensor.TYPE_ACCELEROMETER
constant. If at least one Sensor exists, it is possible to register a SensorEventListener for a Sensor of the list. It
is possible to specify the delivering rate for sensor events. Specified rate must be one of :

    1.   SensorManager.SENSOR_DELAY_FASTEST : as fast as possible
    2.   SensorManager.SENSOR_DELAY_GAME : rate suitable for game
    3.   SensorManager.SENSOR_DELAY_NORMAL : normal rate
    4.   SensorManager.SENSOR_DELAY_UI : rate suitable for UI Thread

In order to allow a correct shake detection, it is preferable to use at least
SensorManager.SENSOR_DELAY_GAME.

The custom accelerometer manager is as follow :

package net.androgames.bolg.sample.accelerometer;

import java.util.List;

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

/**
 * Android Accelerometer Sensor Manager Archetype
 * @author antoine vianey
 * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
 */
public class AccelerometerManager {

     /** Accuracy configuration */
     private static float threshold                = 0.2f;
     private static int interval                = 1000;

                             A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
private static Sensor sensor;
private static SensorManager sensorManager;
// you could use an OrientationListener array instead
// if you plans to use more than one listener
private static AccelerometerListener listener;

/** indicates whether or not Accelerometer Sensor is supported */
private static Boolean supported;
/** indicates whether or not Accelerometer Sensor is running */
private static boolean running = false;

/**
  * Returns true if the manager is listening to orientation changes
  */
public static boolean isListening() {
     return running;
}

/**
  * Unregisters listeners
  */
public static void stopListening() {
     running = false;
     try {
         if (sensorManager != null && sensorEventListener != null) {
             sensorManager.unregisterListener(sensorEventListener);
         }
     } catch (Exception e) {}
}

/**
  * Returns true if at least one Accelerometer sensor is available
  */
public static boolean isSupported() {
     if (supported == null) {
         if (Accelerometer.getContext() != null) {
             sensorManager = (SensorManager) Accelerometer.getContext().
                     getSystemService(Context.SENSOR_SERVICE);
             List<Sensor> sensors = sensorManager.getSensorList(
                     Sensor.TYPE_ACCELEROMETER);
             supported = new Boolean(sensors.size() > 0);
         } else {
             supported = Boolean.FALSE;
         }
     }
     return supported;
}

/**
  * Configure the listener for shaking
  * @param threshold
  *             minimum acceleration variation for considering shaking
  * @param interval
  *             minimum interval between to shake events
  */
public static void configure(int threshold, int interval) {
     AccelerometerManager.threshold = threshold;
     AccelerometerManager.interval = interval;
}



                  A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
/**
  * Registers a listener and start listening
  * @param accelerometerListener
  *             callback for accelerometer events
  */
public static void startListening(
         AccelerometerListener accelerometerListener) {
     sensorManager = (SensorManager) Accelerometer.getContext().
             getSystemService(Context.SENSOR_SERVICE);
     List<Sensor> sensors = sensorManager.getSensorList(
             Sensor.TYPE_ACCELEROMETER);
     if (sensors.size() > 0) {
         sensor = sensors.get(0);
         running = sensorManager.registerListener(
                 sensorEventListener, sensor,
                 SensorManager.SENSOR_DELAY_GAME);
         listener = accelerometerListener;
     }
}

/**
  * Configures threshold and interval
  * And registers a listener and start listening
  * @param accelerometerListener
  *             callback for accelerometer events
  * @param threshold
  *             minimum acceleration variation for considering shaking
  * @param interval
  *             minimum interval between to shake events
  */
public static void startListening(
         AccelerometerListener accelerometerListener,
         int threshold, int interval) {
     configure(threshold, interval);
     startListening(accelerometerListener);
}

/**
 * The listener that listen to events from the accelerometer listener
 */
private static SensorEventListener sensorEventListener =
    new SensorEventListener() {

    private   long    now = 0;
    private   long    timeDiff = 0;
    private   long    lastUpdate = 0;
    private   long    lastShake = 0;

    private   float   x = 0;
    private   float   y = 0;
    private   float   z = 0;
    private   float   lastX =   0;
    private   float   lastY =   0;
    private   float   lastZ =   0;
    private   float   force =   0;

    public void onAccuracyChanged(Sensor sensor, int accuracy) {}

    public void onSensorChanged(SensorEvent event) {
        // use the event timestamp as reference
        // so the manager precision won't depends


                       A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
// on the AccelerometerListener implementation
               // processing time
               now = event.timestamp;

               x = event.values[0];
               y = event.values[1];
               z = event.values[2];

               // if not interesting in shake events
               // just remove the whole if then else bloc
               if (lastUpdate == 0) {
                   lastUpdate = now;
                   lastShake = now;
                   lastX = x;
                   lastY = y;
                   lastZ = z;
               } else {
                   timeDiff = now - lastUpdate;
                   if (timeDiff > 0) {
                        force = Math.abs(x + y + z - lastX - lastY - lastZ)
                                    / timeDiff;
                        if (force > threshold) {
                            if (now - lastShake >= interval) {
                                // trigger shake event
                                listener.onShake(force);
                            }
                            lastShake = now;
                        }
                        lastX = x;
                        lastY = y;
                        lastZ = z;
                        lastUpdate = now;
                   }
               }
               // trigger change event
               listener.onAccelerationChanged(x, y, z);
          }

     };

}

In the case of a SensorEvent triggered by a Sensor of type Sensor.TYPE_ACCELEROMETER, the event’s
values represents the acceleration of the phone given by a vector in a cartesian coordinate system. Landing on a
table, the values returned by the SensorEvent for the phone should be :

    1. 0 m/s2 along x axis
    2. 0 m/s2 along y axis
    3. 9,80665 m/s2 along z axis

From an event to another, the coordinates of the acceleration vector are stored to detect suddent acceleration
changes and to trigger a shake event when the threshold is reached. Others events could be implemented such
as the detection of up and down gestures, circular gestures and lot more…

The custom AccelerometerManager can be use in any Activity or Service :

package net.androgames.bolg.sample.accelerometer;


                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
import   android.app.Activity;
import   android.content.Context;
import   android.os.Bundle;
import   android.widget.TextView;
import   android.widget.Toast;

/**
 * Android accelerometer sensor tutorial
 * @author antoine vianey
 * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
 */
public class Accelerometer extends Activity
        implements AccelerometerListener {

    private static Context CONTEXT;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        CONTEXT = this;
    }

    protected void onResume() {
        super.onResume();
        if (AccelerometerManager.isSupported()) {
            AccelerometerManager.startListening(this);
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        if (AccelerometerManager.isListening()) {
            AccelerometerManager.stopListening();
        }

    }

    public static Context getContext() {
        return CONTEXT;
    }

    /**
      * onShake callback
      */
    public void onShake(float force) {
         Toast.makeText(this, "Phone shaked : " + force, 1000).show();
    }

    /**
      * onAccelerationChanged callback
      */
    public void onAccelerationChanged(float x, float y, float z) {
         ((TextView) findViewById(R.id.x)).setText(String.valueOf(x));
         ((TextView) findViewById(R.id.y)).setText(String.valueOf(y));
         ((TextView) findViewById(R.id.z)).setText(String.valueOf(z));
    }

}



                        A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
As usual, it is preferable to register listeners in the onResume() method of the Activity and removed in the
onFinish() method of the Activity.




Android Orientation Sensor tutorial
Posted by Tonio | Filed under Tutorial

Android phones includes an orientation sensor that is used to detect the orientation of the phone in space. The
orientation is given throught three values :

   1. Azimtuh in degres
      angle between the x axis of the phone and the north direction
      0 ≤ azimuth ≤ 360
   2. Pitch in degres
      angle made by the y axis of the phone relatively to the phone’s horizontal position
      -180 ≤ pitch ≤ 180
   3. Roll in degres
      angle made by the x axis of the phone relatively to the phone’s horizontal position
      -90 ≤ roll ≤ 90

In this tutorial, we’ll see how to use the orientation sensor in an application in order to capture orientation
change events. We’ll use these events to build a custom listener that will trigger phone’s orientation change
events :

package net.androgames.blog.sample.orientation;

public interface OrientationListener {

     public void onOrientationChanged(float azimuth,
             float pitch, float roll);

     /**
      * Top side of the phone is up
      * The phone is standing on its bottom side
      */
     public void onTopUp();

     /**
      * Bottom side of the phone is up
      * The phone is standing on its top side
      */
     public void onBottomUp();

     /**
      * Right side of the phone is up
      * The phone is standing on its left side
      */
     public void onRightUp();

     /**
      * Left side of the phone is up
      * The phone is standing on its right side
      */

                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
public void onLeftUp();

}

An instance of the SensorManager is needed in order to retrieve informations about the supported sensors. No
permission is required to access the sensor service and to retrieve the list of available orientation sensors given
by the Sensor.TYPE_ORIENTATION constant. If at least one Sensor exists, it is possible to register a
SensorEventListener for a Sensor of the list. The delivering rate for the orientation sensor events can be
specified and must be one of these :

    1.   SensorManager.SENSOR_DELAY_FASTEST : as fast as possible
    2.   SensorManager.SENSOR_DELAY_GAME : rate suitable for game
    3.   SensorManager.SENSOR_DELAY_NORMAL : normal rate
    4.   SensorManager.SENSOR_DELAY_UI : rate suitable for UI Thread

The custom orientation manager is as follow :

package net.androgames.blog.sample.orientation;

import java.util.List;

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

/**
 * Android Orientation Sensor Manager Archetype
 * @author antoine vianey
 * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
 */
public class OrientationManager {

     private static Sensor sensor;
     private static SensorManager sensorManager;
     // you could use an OrientationListener array instead
     // if you plans to use more than one listener
     private static OrientationListener listener;

     /** indicates whether or not Orientation Sensor is supported */
     private static Boolean supported;
     /** indicates whether or not Orientation Sensor is running */
     private static boolean running = false;

     /** Sides of the phone */
     enum Side {
         TOP,
         BOTTOM,
         LEFT,
         RIGHT;
     }

     /**
      * Returns true if the manager is listening to orientation changes
      */
     public static boolean isListening() {
         return running;

                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
}

/**
  * Unregisters listeners
  */
public static void stopListening() {
     running = false;
     try {
         if (sensorManager != null && sensorEventListener != null) {
             sensorManager.unregisterListener(sensorEventListener);
         }
     } catch (Exception e) {}
}

/**
  * Returns true if at least one Orientation sensor is available
  */
public static boolean isSupported() {
     if (supported == null) {
         if (Orientation.getContext() != null) {
             sensorManager = (SensorManager) Orientation.getContext()
                     .getSystemService(Context.SENSOR_SERVICE);
             List<Sensor> sensors = sensorManager.getSensorList(
                     Sensor.TYPE_ORIENTATION);
             supported = new Boolean(sensors.size() > 0);
         } else {
             supported = Boolean.FALSE;
         }
     }
     return supported;
}

/**
  * Registers a listener and start listening
  */
public static void startListening(
         OrientationListener orientationListener) {
     sensorManager = (SensorManager) Orientation.getContext()
             .getSystemService(Context.SENSOR_SERVICE);
     List<Sensor> sensors = sensorManager.getSensorList(
             Sensor.TYPE_ORIENTATION);
     if (sensors.size() > 0) {
         sensor = sensors.get(0);
         running = sensorManager.registerListener(
                 sensorEventListener, sensor,
                 SensorManager.SENSOR_DELAY_NORMAL);
         listener = orientationListener;
     }
}

/**
 * The listener that listen to events from the orientation listener
 */
private static SensorEventListener sensorEventListener =
    new SensorEventListener() {

    /** The   side that is currently up */
    private   Side currentSide = null;
    private   Side oldSide = null;
    private   float azimuth;
    private   float pitch;


                    A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
private float roll;

           public void onAccuracyChanged(Sensor sensor, int accuracy) {}

           public void onSensorChanged(SensorEvent event) {

               azimuth = event.values[0];         // azimuth
               pitch = event.values[1];         // pitch
               roll = event.values[2];            // roll

               if (pitch < -45 && pitch > -135) {
                   // top side up
                   currentSide = Side.TOP;
               } else if (pitch > 45 && pitch < 135) {
                   // bottom side up
                   currentSide = Side.BOTTOM;
               } else if (roll > 45) {
                   // right side up
                   currentSide = Side.RIGHT;
               } else if (roll < -45) {
                   // left side up
                   currentSide = Side.LEFT;
               }

               if (currentSide != null && !currentSide.equals(oldSide)) {
                   switch (currentSide) {
                       case TOP :
                           listener.onTopUp();
                           break;
                       case BOTTOM :
                           listener.onBottomUp();
                           break;
                       case LEFT:
                           listener.onLeftUp();
                           break;
                       case RIGHT:
                           listener.onRightUp();
                           break;
                   }
                   oldSide = currentSide;
               }

               // forwards orientation to the OrientationListener
               listener.onOrientationChanged(azimuth, pitch, roll);
           }

      };

}

The custom OrientationManager can be use in any Activity or Service :

package net.androgames.blog.sample.orientation;

import     android.app.Activity;
import     android.content.Context;
import     android.os.Bundle;
import     android.widget.TextView;
import     android.widget.Toast;

/**

                          A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
* Android orientation sensor tutorial
 * @author antoine vianey
 * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
 */
public class Orientation extends Activity implements OrientationListener {

    private static Context CONTEXT;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        CONTEXT = this;
    }

    protected void onResume() {
        super.onResume();
        if (OrientationManager.isSupported()) {
            OrientationManager.startListening(this);
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        if (OrientationManager.isListening()) {
            OrientationManager.stopListening();
        }

    }

    public static Context getContext() {
        return CONTEXT;
    }

    @Override
    public void onOrientationChanged(float azimuth,
            float pitch, float roll) {
        ((TextView) findViewById(R.id.azimuth)).setText(
                String.valueOf(azimuth));
        ((TextView) findViewById(R.id.pitch)).setText(
                String.valueOf(pitch));
        ((TextView) findViewById(R.id.roll)).setText(
                String.valueOf(roll));
    }

    @Override
    public void onBottomUp() {
        Toast.makeText(this, "Bottom UP", 1000).show();
    }

    @Override
    public void onLeftUp() {
        Toast.makeText(this, "Left UP", 1000).show();
    }

    @Override
    public void onRightUp() {
        Toast.makeText(this, "Right UP", 1000).show();
    }

    @Override


                      A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
public void onTopUp() {
         Toast.makeText(this, "Top UP", 1000).show();
     }

}

As usual, it is preferable to register listeners in the onResume() method of the Activity and removed in the
onFinish() method of the Activity.




                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

More Related Content

Similar to Android accelerometer sensor tutorial

SlingShot._slingShot.swfSlingShotaccelerometer.asimport .docx
SlingShot._slingShot.swfSlingShotaccelerometer.asimport .docxSlingShot._slingShot.swfSlingShotaccelerometer.asimport .docx
SlingShot._slingShot.swfSlingShotaccelerometer.asimport .docxbudabrooks46239
 
Android sensors
Android sensorsAndroid sensors
Android sensorsdatta_jini
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - eventsroxlu
 
Introdução à programação orientada para aspectos
Introdução à programação orientada para aspectosIntrodução à programação orientada para aspectos
Introdução à programação orientada para aspectosManuel Menezes de Sequeira
 
Android Architecture Component in Real Life
Android Architecture Component in Real LifeAndroid Architecture Component in Real Life
Android Architecture Component in Real LifeSomkiat Khitwongwattana
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3Jieyi Wu
 
Sensing Mobile Devices talk from QCon London 2013
Sensing Mobile Devices talk from QCon London 2013Sensing Mobile Devices talk from QCon London 2013
Sensing Mobile Devices talk from QCon London 2013Adam Blum
 
Trisha gee concurrentprogrammingusingthedisruptor
Trisha gee concurrentprogrammingusingthedisruptorTrisha gee concurrentprogrammingusingthedisruptor
Trisha gee concurrentprogrammingusingthedisruptorEthanTu
 
DomCode 2015 - Abusing phones to make the internet of things
DomCode 2015 - Abusing phones to make the internet of thingsDomCode 2015 - Abusing phones to make the internet of things
DomCode 2015 - Abusing phones to make the internet of thingsJan Jongboom
 
Timers in Unix/Linux
Timers in Unix/LinuxTimers in Unix/Linux
Timers in Unix/Linuxgeeksrik
 
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdfplease send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdfFashionBoutiquedelhi
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to RxAndrey Cheptsov
 

Similar to Android accelerometer sensor tutorial (20)

Ext J S Observable
Ext J S ObservableExt J S Observable
Ext J S Observable
 
Android wearpp
Android wearppAndroid wearpp
Android wearpp
 
SlingShot._slingShot.swfSlingShotaccelerometer.asimport .docx
SlingShot._slingShot.swfSlingShotaccelerometer.asimport .docxSlingShot._slingShot.swfSlingShotaccelerometer.asimport .docx
SlingShot._slingShot.swfSlingShotaccelerometer.asimport .docx
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Android sensors
Android sensorsAndroid sensors
Android sensors
 
2 презентация rx java+android
2 презентация rx java+android2 презентация rx java+android
2 презентация rx java+android
 
Ext oo
Ext ooExt oo
Ext oo
 
NWD the73js.pptx
NWD the73js.pptxNWD the73js.pptx
NWD the73js.pptx
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - events
 
Introdução à programação orientada para aspectos
Introdução à programação orientada para aspectosIntrodução à programação orientada para aspectos
Introdução à programação orientada para aspectos
 
Android Architecture Component in Real Life
Android Architecture Component in Real LifeAndroid Architecture Component in Real Life
Android Architecture Component in Real Life
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3
 
Sensing Mobile Devices talk from QCon London 2013
Sensing Mobile Devices talk from QCon London 2013Sensing Mobile Devices talk from QCon London 2013
Sensing Mobile Devices talk from QCon London 2013
 
Trisha gee concurrentprogrammingusingthedisruptor
Trisha gee concurrentprogrammingusingthedisruptorTrisha gee concurrentprogrammingusingthedisruptor
Trisha gee concurrentprogrammingusingthedisruptor
 
DomCode 2015 - Abusing phones to make the internet of things
DomCode 2015 - Abusing phones to make the internet of thingsDomCode 2015 - Abusing phones to make the internet of things
DomCode 2015 - Abusing phones to make the internet of things
 
Timers in Unix/Linux
Timers in Unix/LinuxTimers in Unix/Linux
Timers in Unix/Linux
 
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdfplease send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
A Playful Introduction to Rx
A Playful Introduction to RxA Playful Introduction to Rx
A Playful Introduction to Rx
 

More from info_zybotech

Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activitiesinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid drawinfo_zybotech
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 

More from info_zybotech (8)

Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activities
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Notepad tutorial
Notepad tutorialNotepad tutorial
Notepad tutorial
 
Java and xml
Java and xmlJava and xml
Java and xml
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
 
Applications
ApplicationsApplications
Applications
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 

Recently uploaded

It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayNZSG
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...amitlee9823
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...lizamodels9
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...lizamodels9
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Sheetaleventcompany
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxpriyanshujha201
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperityhemanthkumar470700
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...Aggregage
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdfRenandantas16
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLkapoorjyoti4444
 
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...lizamodels9
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableSeo
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfAmzadHosen3
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Serviceritikaroy0888
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptxnandhinijagan9867
 

Recently uploaded (20)

It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 
Falcon Invoice Discounting platform in india
Falcon Invoice Discounting platform in indiaFalcon Invoice Discounting platform in india
Falcon Invoice Discounting platform in india
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperity
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLBAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
BAGALUR CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
 
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
John Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdfJohn Halpern sued for sexual assault.pdf
John Halpern sued for sexual assault.pdf
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 

Android accelerometer sensor tutorial

  • 1. Android Application Development Training Tutorial For more info visit http://www.zybotech.in A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 2. Android Accelerometer Sensor tutorial Android supports a wide variety of sensors that can be used by applications to capture informations about the phone’s environment. In this tutorial, we’ll see how to use the accelerometer sensor in an application in order to capture acceleration change events. We’ll use these events to build a custom listener that will trigger others events such as shake events : package net.androgames.bolg.sample.accelerometer; public interface AccelerometerListener { public void onAccelerationChanged(float x, float y, float z); public void onShake(float force); } An instance of the SensorManager is required in order to retrieve informations about the supported sensors. No permission is required to access the sensor service. It is then possible to retrieve the list of available sensors of a certain type. For an accelerometer sensor, the type to use is given by the Sensor.TYPE_ACCELEROMETER constant. If at least one Sensor exists, it is possible to register a SensorEventListener for a Sensor of the list. It is possible to specify the delivering rate for sensor events. Specified rate must be one of : 1. SensorManager.SENSOR_DELAY_FASTEST : as fast as possible 2. SensorManager.SENSOR_DELAY_GAME : rate suitable for game 3. SensorManager.SENSOR_DELAY_NORMAL : normal rate 4. SensorManager.SENSOR_DELAY_UI : rate suitable for UI Thread In order to allow a correct shake detection, it is preferable to use at least SensorManager.SENSOR_DELAY_GAME. The custom accelerometer manager is as follow : package net.androgames.bolg.sample.accelerometer; import java.util.List; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * Android Accelerometer Sensor Manager Archetype * @author antoine vianey * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html */ public class AccelerometerManager { /** Accuracy configuration */ private static float threshold = 0.2f; private static int interval = 1000; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 3. private static Sensor sensor; private static SensorManager sensorManager; // you could use an OrientationListener array instead // if you plans to use more than one listener private static AccelerometerListener listener; /** indicates whether or not Accelerometer Sensor is supported */ private static Boolean supported; /** indicates whether or not Accelerometer Sensor is running */ private static boolean running = false; /** * Returns true if the manager is listening to orientation changes */ public static boolean isListening() { return running; } /** * Unregisters listeners */ public static void stopListening() { running = false; try { if (sensorManager != null && sensorEventListener != null) { sensorManager.unregisterListener(sensorEventListener); } } catch (Exception e) {} } /** * Returns true if at least one Accelerometer sensor is available */ public static boolean isSupported() { if (supported == null) { if (Accelerometer.getContext() != null) { sensorManager = (SensorManager) Accelerometer.getContext(). getSystemService(Context.SENSOR_SERVICE); List<Sensor> sensors = sensorManager.getSensorList( Sensor.TYPE_ACCELEROMETER); supported = new Boolean(sensors.size() > 0); } else { supported = Boolean.FALSE; } } return supported; } /** * Configure the listener for shaking * @param threshold * minimum acceleration variation for considering shaking * @param interval * minimum interval between to shake events */ public static void configure(int threshold, int interval) { AccelerometerManager.threshold = threshold; AccelerometerManager.interval = interval; } A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 4. /** * Registers a listener and start listening * @param accelerometerListener * callback for accelerometer events */ public static void startListening( AccelerometerListener accelerometerListener) { sensorManager = (SensorManager) Accelerometer.getContext(). getSystemService(Context.SENSOR_SERVICE); List<Sensor> sensors = sensorManager.getSensorList( Sensor.TYPE_ACCELEROMETER); if (sensors.size() > 0) { sensor = sensors.get(0); running = sensorManager.registerListener( sensorEventListener, sensor, SensorManager.SENSOR_DELAY_GAME); listener = accelerometerListener; } } /** * Configures threshold and interval * And registers a listener and start listening * @param accelerometerListener * callback for accelerometer events * @param threshold * minimum acceleration variation for considering shaking * @param interval * minimum interval between to shake events */ public static void startListening( AccelerometerListener accelerometerListener, int threshold, int interval) { configure(threshold, interval); startListening(accelerometerListener); } /** * The listener that listen to events from the accelerometer listener */ private static SensorEventListener sensorEventListener = new SensorEventListener() { private long now = 0; private long timeDiff = 0; private long lastUpdate = 0; private long lastShake = 0; private float x = 0; private float y = 0; private float z = 0; private float lastX = 0; private float lastY = 0; private float lastZ = 0; private float force = 0; public void onAccuracyChanged(Sensor sensor, int accuracy) {} public void onSensorChanged(SensorEvent event) { // use the event timestamp as reference // so the manager precision won't depends A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 5. // on the AccelerometerListener implementation // processing time now = event.timestamp; x = event.values[0]; y = event.values[1]; z = event.values[2]; // if not interesting in shake events // just remove the whole if then else bloc if (lastUpdate == 0) { lastUpdate = now; lastShake = now; lastX = x; lastY = y; lastZ = z; } else { timeDiff = now - lastUpdate; if (timeDiff > 0) { force = Math.abs(x + y + z - lastX - lastY - lastZ) / timeDiff; if (force > threshold) { if (now - lastShake >= interval) { // trigger shake event listener.onShake(force); } lastShake = now; } lastX = x; lastY = y; lastZ = z; lastUpdate = now; } } // trigger change event listener.onAccelerationChanged(x, y, z); } }; } In the case of a SensorEvent triggered by a Sensor of type Sensor.TYPE_ACCELEROMETER, the event’s values represents the acceleration of the phone given by a vector in a cartesian coordinate system. Landing on a table, the values returned by the SensorEvent for the phone should be : 1. 0 m/s2 along x axis 2. 0 m/s2 along y axis 3. 9,80665 m/s2 along z axis From an event to another, the coordinates of the acceleration vector are stored to detect suddent acceleration changes and to trigger a shake event when the threshold is reached. Others events could be implemented such as the detection of up and down gestures, circular gestures and lot more… The custom AccelerometerManager can be use in any Activity or Service : package net.androgames.bolg.sample.accelerometer; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 6. import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; /** * Android accelerometer sensor tutorial * @author antoine vianey * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html */ public class Accelerometer extends Activity implements AccelerometerListener { private static Context CONTEXT; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); CONTEXT = this; } protected void onResume() { super.onResume(); if (AccelerometerManager.isSupported()) { AccelerometerManager.startListening(this); } } protected void onDestroy() { super.onDestroy(); if (AccelerometerManager.isListening()) { AccelerometerManager.stopListening(); } } public static Context getContext() { return CONTEXT; } /** * onShake callback */ public void onShake(float force) { Toast.makeText(this, "Phone shaked : " + force, 1000).show(); } /** * onAccelerationChanged callback */ public void onAccelerationChanged(float x, float y, float z) { ((TextView) findViewById(R.id.x)).setText(String.valueOf(x)); ((TextView) findViewById(R.id.y)).setText(String.valueOf(y)); ((TextView) findViewById(R.id.z)).setText(String.valueOf(z)); } } A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 7. As usual, it is preferable to register listeners in the onResume() method of the Activity and removed in the onFinish() method of the Activity. Android Orientation Sensor tutorial Posted by Tonio | Filed under Tutorial Android phones includes an orientation sensor that is used to detect the orientation of the phone in space. The orientation is given throught three values : 1. Azimtuh in degres angle between the x axis of the phone and the north direction 0 ≤ azimuth ≤ 360 2. Pitch in degres angle made by the y axis of the phone relatively to the phone’s horizontal position -180 ≤ pitch ≤ 180 3. Roll in degres angle made by the x axis of the phone relatively to the phone’s horizontal position -90 ≤ roll ≤ 90 In this tutorial, we’ll see how to use the orientation sensor in an application in order to capture orientation change events. We’ll use these events to build a custom listener that will trigger phone’s orientation change events : package net.androgames.blog.sample.orientation; public interface OrientationListener { public void onOrientationChanged(float azimuth, float pitch, float roll); /** * Top side of the phone is up * The phone is standing on its bottom side */ public void onTopUp(); /** * Bottom side of the phone is up * The phone is standing on its top side */ public void onBottomUp(); /** * Right side of the phone is up * The phone is standing on its left side */ public void onRightUp(); /** * Left side of the phone is up * The phone is standing on its right side */ A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 8. public void onLeftUp(); } An instance of the SensorManager is needed in order to retrieve informations about the supported sensors. No permission is required to access the sensor service and to retrieve the list of available orientation sensors given by the Sensor.TYPE_ORIENTATION constant. If at least one Sensor exists, it is possible to register a SensorEventListener for a Sensor of the list. The delivering rate for the orientation sensor events can be specified and must be one of these : 1. SensorManager.SENSOR_DELAY_FASTEST : as fast as possible 2. SensorManager.SENSOR_DELAY_GAME : rate suitable for game 3. SensorManager.SENSOR_DELAY_NORMAL : normal rate 4. SensorManager.SENSOR_DELAY_UI : rate suitable for UI Thread The custom orientation manager is as follow : package net.androgames.blog.sample.orientation; import java.util.List; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * Android Orientation Sensor Manager Archetype * @author antoine vianey * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html */ public class OrientationManager { private static Sensor sensor; private static SensorManager sensorManager; // you could use an OrientationListener array instead // if you plans to use more than one listener private static OrientationListener listener; /** indicates whether or not Orientation Sensor is supported */ private static Boolean supported; /** indicates whether or not Orientation Sensor is running */ private static boolean running = false; /** Sides of the phone */ enum Side { TOP, BOTTOM, LEFT, RIGHT; } /** * Returns true if the manager is listening to orientation changes */ public static boolean isListening() { return running; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 9. } /** * Unregisters listeners */ public static void stopListening() { running = false; try { if (sensorManager != null && sensorEventListener != null) { sensorManager.unregisterListener(sensorEventListener); } } catch (Exception e) {} } /** * Returns true if at least one Orientation sensor is available */ public static boolean isSupported() { if (supported == null) { if (Orientation.getContext() != null) { sensorManager = (SensorManager) Orientation.getContext() .getSystemService(Context.SENSOR_SERVICE); List<Sensor> sensors = sensorManager.getSensorList( Sensor.TYPE_ORIENTATION); supported = new Boolean(sensors.size() > 0); } else { supported = Boolean.FALSE; } } return supported; } /** * Registers a listener and start listening */ public static void startListening( OrientationListener orientationListener) { sensorManager = (SensorManager) Orientation.getContext() .getSystemService(Context.SENSOR_SERVICE); List<Sensor> sensors = sensorManager.getSensorList( Sensor.TYPE_ORIENTATION); if (sensors.size() > 0) { sensor = sensors.get(0); running = sensorManager.registerListener( sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL); listener = orientationListener; } } /** * The listener that listen to events from the orientation listener */ private static SensorEventListener sensorEventListener = new SensorEventListener() { /** The side that is currently up */ private Side currentSide = null; private Side oldSide = null; private float azimuth; private float pitch; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 10. private float roll; public void onAccuracyChanged(Sensor sensor, int accuracy) {} public void onSensorChanged(SensorEvent event) { azimuth = event.values[0]; // azimuth pitch = event.values[1]; // pitch roll = event.values[2]; // roll if (pitch < -45 && pitch > -135) { // top side up currentSide = Side.TOP; } else if (pitch > 45 && pitch < 135) { // bottom side up currentSide = Side.BOTTOM; } else if (roll > 45) { // right side up currentSide = Side.RIGHT; } else if (roll < -45) { // left side up currentSide = Side.LEFT; } if (currentSide != null && !currentSide.equals(oldSide)) { switch (currentSide) { case TOP : listener.onTopUp(); break; case BOTTOM : listener.onBottomUp(); break; case LEFT: listener.onLeftUp(); break; case RIGHT: listener.onRightUp(); break; } oldSide = currentSide; } // forwards orientation to the OrientationListener listener.onOrientationChanged(azimuth, pitch, roll); } }; } The custom OrientationManager can be use in any Activity or Service : package net.androgames.blog.sample.orientation; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; /** A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 11. * Android orientation sensor tutorial * @author antoine vianey * under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html */ public class Orientation extends Activity implements OrientationListener { private static Context CONTEXT; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); CONTEXT = this; } protected void onResume() { super.onResume(); if (OrientationManager.isSupported()) { OrientationManager.startListening(this); } } protected void onDestroy() { super.onDestroy(); if (OrientationManager.isListening()) { OrientationManager.stopListening(); } } public static Context getContext() { return CONTEXT; } @Override public void onOrientationChanged(float azimuth, float pitch, float roll) { ((TextView) findViewById(R.id.azimuth)).setText( String.valueOf(azimuth)); ((TextView) findViewById(R.id.pitch)).setText( String.valueOf(pitch)); ((TextView) findViewById(R.id.roll)).setText( String.valueOf(roll)); } @Override public void onBottomUp() { Toast.makeText(this, "Bottom UP", 1000).show(); } @Override public void onLeftUp() { Toast.makeText(this, "Left UP", 1000).show(); } @Override public void onRightUp() { Toast.makeText(this, "Right UP", 1000).show(); } @Override A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 12. public void onTopUp() { Toast.makeText(this, "Top UP", 1000).show(); } } As usual, it is preferable to register listeners in the onResume() method of the Activity and removed in the onFinish() method of the Activity. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi