There are several examples and tutorials on the Internet, but be careful. Sensor.TYPE_ORIENTATION deprecated. You must calculate the rotations by listening to the two sensors Sensor.TYPE_ACCELEROMETER and Sensor.TYPE_MAGNETIC_FIELD .
The challenge after registering to receive notifications from these sensors is to figure out how to process the data received from them. The key part is the following:
public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) mGravity = event.values; if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) mGeomagnetic = event.values; if (mGravity != null && mGeomagnetic != null) { float R[] = new float[9]; float I[] = new float[9]; boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic); if (success) { float orientation[] = new float[3]; SensorManager.getOrientation(R, orientation); azimuth = orientation[0];
Here is how you should calculate the azimuth, step, roll of your device in onSensorChanged(SensorEvent event) . Keep in mind that "All three angles are higher in radians and are positive in the counterclockwise direction." You can simply convert them to degrees using Math.toDegrees()
As Louis CAD pointed out in the comments, it would be nice to override the initialization of I, R arrays and orientations from the onSensorChanged callback, as it is often called. Creating and leaving them for the GC has a bad effect on the performance of your applications. I left it there for the sake of simplicity.
Depending on how your device rotates, you may need to reassign the coordinates to get the desired result. You can read more about remapCoordinateSystem and also about getRotationMatrix and getOrientation in the Android documentation
Example code: http://www.codingforandroid.com/2011/01/using-orientation-sensors-simple.html
Csaba szugyiczki
source share