Created
November 13, 2016 22:53
-
-
Save labe-me/997f52b44795208dd7313f82ba67168c to your computer and use it in GitHub Desktop.
Getting android device orientation relatively to north
This file contains 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
package android | |
import android.app.Activity | |
import android.content.Context | |
import android.hardware._ | |
/** Listen to device Orientation changes. | |
* | |
* Note: if you use libgdx your the work is already done in Gdx.input.getRotationMatrix() and Gdx.input.getPitch() | |
*/ | |
class OrientationTracker(activity: Activity) extends SensorEventListener { | |
private val manager = activity.getSystemService(Context.SENSOR_SERVICE).asInstanceOf[SensorManager] | |
private val magneticSensor = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) | |
private var magneticReady = false | |
private val magneticValues = new Array[Float](3) | |
private val accelerometerSensor = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) | |
private var accelerometerReady = false | |
private val accelerometerValues = new Array[Float](3) | |
private val rotationMatrix = new Array[Float](16) | |
private val inclinationMatrix = new Array[Float](16) | |
private val orientationVector = new Array[Float](3) | |
var orientation: Option[Double] = None | |
def onDestroy() = { | |
manager.unregisterListener(this) | |
} | |
def onResume() = { | |
magneticReady = false | |
accelerometerReady = false | |
manager.registerListener(this, magneticSensor, SensorManager.SENSOR_DELAY_GAME) | |
manager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME) | |
() | |
} | |
def onPause() = { | |
manager.unregisterListener(this) | |
} | |
override def onAccuracyChanged(sensor: Sensor, value: Int) = { | |
} | |
override def onSensorChanged(event: SensorEvent) = { | |
event.sensor.getType match { | |
case Sensor.TYPE_ACCELEROMETER => | |
accelerometerReady = true | |
System.arraycopy(event.values, 0, accelerometerValues, 0, 3) | |
case Sensor.TYPE_MAGNETIC_FIELD => | |
magneticReady = true | |
System.arraycopy(event.values, 0, magneticValues, 0, 3) | |
} | |
if (accelerometerReady && magneticReady){ | |
val success = SensorManager.getRotationMatrix(rotationMatrix, inclinationMatrix, accelerometerValues, magneticValues) | |
if (success){ | |
SensorManager.getOrientation(rotationMatrix, orientationVector) | |
orientation = Some(orientationVector(0).toDouble) | |
} | |
accelerometerReady = false | |
magneticReady = false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment