Every time I open my app, I get the device's orientation values. If I turn the device 90 degrees to the right at the X-axis, the values change as well. But every time I reopen my app, it shows that the X value is 348. Even if I rotated the phone 90 degrees before opening my app. Why do the sensors return the same value at the start?
Whu every time I entry the app, the starting points are always the same?
I rotated the device before opening the app to 0 degrees and got:
I rotated the device before opening the app to 90 degrees and got:
I'm rotating the correct axis, this is not the problem
My code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sensorManager.registerListener(MainActivity.this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
public void onSensorChanged(SensorEvent event) { // Activated every changes in sensors
Log.i(TAG, event.values[0] + " | " + event.values[1] + " | " + event.values[2]); // Prit the sensors values
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
Does this do what you wanted it to do?
I am just registering the listener in onStart
and unregistering the listener in onStop
and reading the sensorEvent
value for the x-axis.
class MainActivity : AppCompatActivity() {
private var sensorManager: SensorManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager?
}
override fun onStart() {
super.onStart()
val sensorAccelerometer = sensorManager?.getDefaultSensor(Sensor.TYPE_ORIENTATION)
if (sensorAccelerometer != null) {
sensorManager?.registerListener(sensorEventListener, sensorAccelerometer, SensorManager.SENSOR_DELAY_UI)
} else {
// No accelerometer available
}
}
override fun onStop() {
super.onStop()
sensorManager?.unregisterListener(sensorEventListener)
}
private val sensorEventListener: SensorEventListener = object : SensorEventListener {
override fun onSensorChanged(sensorEvent: SensorEvent?) {
val rotationX = sensorEvent?.values?.get(0)?.toInt()
// I am writing the int value to a TextView in the UI
findViewById<TextView>(R.id.text_view_rotation_x).text = String.format(Locale.ENGLISH, "$rotationX")
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
// Do something
}
}
}