Created
November 12, 2014 16:43
-
-
Save rogerpujol/8e6e7a75337276ed608c to your computer and use it in GitHub Desktop.
In this example you will see how to create, register & unregister a SensorListener, in this example we focus on Gyroscope Sensor.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create a GYROSCOPE SENSOR Listener | |
* Check for more info: http://developer.android.com/guide/topics/sensors/sensors_motion.html | |
*/ | |
private SensorManager mSensorService; | |
private Sensor mSensor; | |
private SensorEventListener mySensorEventListener; | |
mySensorEventListener = new SensorEventListener() { | |
@Override | |
public void onAccuracyChanged(Sensor sensor, int accuracy) { | |
} | |
@Override | |
public void onSensorChanged(SensorEvent event) { | |
Log.v("SENSOR",event.values[0]+" "+event.values[1]+" "+event.values[2]); | |
} | |
}; | |
mSensorService = (SensorManager) getSystemService(Context.SENSOR_SERVICE); | |
mSensor = mSensorService.getDefaultSensor(Sensor.TYPE_GYROSCOPE); | |
if (mSensor != null) { | |
mSensorService.registerListener(mySensorEventListener, mSensor, | |
SensorManager.SENSOR_DELAY_NORMAL); | |
Log.i("Compass MainActivity", "Registerered for GYROSCOPE Sensor"); | |
} else { | |
Log.e("Compass MainActivity", "Registerered for GYROSCOPE Sensor"); | |
Toast.makeText(this, "ORIENTATION Sensor not found", | |
Toast.LENGTH_LONG).show(); | |
/** | |
* Call finish(); only if you want to close your activity right away... | |
*/ | |
//finish(); | |
} | |
/** | |
* IMPORANT!!!! | |
* Unregister Listener onDestroy(), onPause() or any other place...don't forget it, we need the resources man! | |
*/ | |
if (mSensor != null) { | |
mSensorService.unregisterListener(mySensorEventListener); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment