Android DRIVER: android driver
1 SensorManager mSensorManager = (SensorManager) getSystemService (SENSOR_SERVICE );
Step 2: Use the getdefasensensor method of SensorManager to obtain the sensor Object of the specified type;
1 Sensor sensor = mSensorManager. getdefasensensor (Sensor. TYPE_GRAVITY); // gravity sensing
Step 3: implement the onSensorChanged and onAccuracyChanged methods of the SensorEventListener interface;
1 SensorEventListenerlsn = new SensorEventListener () {2 public void onSensorChanged (SensorEvent e) {3 // when the sensor value changes, will execute here 4} 5 6 public void onAccuracyChanged (Sensor s, int accuracy) {7 // when the Sensor's precision changes, will execute here 8} 9 };
Step 4: register the listener using the registerListener method of SensorManager to obtain the sensor change value.
1 mSensorManager.registerListener(lsn,sensor, SensorManager.SENSOR_DELAY_GAME);
Note: When the sensor value changes, the onSensorChanged method is called. When the sensor's precision changes, the onAccuracyChanged method is called.
Complete sample code:
1 public class main extends Activity { 2 private float x, y, z; 3 protected void onCreate(Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 SensorManager mSensorManager= (SensorManager) getSystemService(SENSOR_SERVICE); 6 Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY); 7 SensorEventListener lsn = new SensorEventListener() { 8 9 public void onSensorChanged(SensorEvent e) { 10 System.out.println(e.value[0]); 11 System.out.println(e.value[1]); 12 System.out.println(e.value[2]); 13 } 14 public void onAccuracyChanged(Sensor s, int accuracy) { 15 } 16 }; 17 mSensorManager.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME); 18 }