I have a small problem with some tests that I am doing in android studio. I am trying to use the gyro sensor of my android device to rotate an image according to the inclination of the device, using the TYPE_ROTATION_VECTOR sensor.
But I'm having a little problem and that is that when you start the application, the sensor is not activated and although the device rotates the application does not work, but instead after a couple of minutes, this sensor is activated and everything works correctly .
Why could this be happening? Because of what I look for and investigate, I do not give with the solution.
Thank you very much.
The code for the main class is as follows
public class MainActivity extends AppCompatActivity {
SensorManager sensorManager;
Sensor giroscopio;
SensorEventListener escucharGiroscopio;
ImageView ivVasom;
Switch sInterruptorm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivVasom = (ImageView) findViewById(R.id.ivVaso);
sInterruptorm = (Switch) findViewById(R.id.sInterruptor);
//Objeto administrador de sensores necesario para utilizar cualquier sensor del dispositivo
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
//Crear objeto del sensor especifico que vamos a utilizar
giroscopio = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
// Create a listener
escucharGiroscopio = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[] rotationMatrix = new float[16];
SensorManager.getRotationMatrixFromVector(rotationMatrix, sensorEvent.values);
// Remap coordinate system
float[] remappedRotationMatrix = new float[16];
SensorManager.remapCoordinateSystem(rotationMatrix,
SensorManager.AXIS_X,
SensorManager.AXIS_Z,
remappedRotationMatrix);
// Convert to orientations
float[] orientations = new float[3];
SensorManager.getOrientation(remappedRotationMatrix, orientations);
for (int i = 0; i < 3; i++) {
orientations[i] = (float) (Math.toDegrees(orientations[i]));
}
Log.d("", "" + orientations[2]);
ivVasom.setRotation(orientations[2] * -1);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
Toast.makeText(this, "e", Toast.LENGTH_SHORT).show();
sensorManager.registerListener(escucharGiroscopio, giroscopio, SensorManager.SENSOR_DELAY_GAME);
}