Why is my variable wrong at the begin of onSensorChanged() call?

108 Views Asked by At

I have this android activity and the goal of the antiLoopMutex variable is to prevent continuous sound play. Unfortunately if the statement sensorEvent.values[0] > 6.0 begins to be always true then antiLoopMutex will be by first 2 calls of onSensorChanged() equal to false instead of being 1 time false and then always true.

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor sensor;
    private MediaPlayer mp;
    private boolean antiLoopMutex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
        mp = MediaPlayer.create(this, R.raw.pseudo_perc);
    }

    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        System.out.println(Arrays.toString(sensorEvent.values));
        if (sensorEvent.values[0] > 6.0) {
            if (!mp.isPlaying() && !antiLoopMutex) {
                System.out.println("[1] Mutex: "+antiLoopMutex);
                antiLoopMutex = true;
                mp.start();
                System.out.println("[2] Mutex: "+antiLoopMutex);
                mp.setOnCompletionListener(mp -> {
                    mp.pause();
                    mp.seekTo(0);
                });
            }
        } else {
            System.out.println("[3]");
            antiLoopMutex = false;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

}

So the current output is:

I/System.out: [0.009788696, 9.753927, 1.0153474]
I/System.out: [3]
I/System.out: [3.0661938, 9.168555, 1.6450276]
I/System.out: [3]
I/System.out: [9.268236, 0.9579816, 3.0581598]
I/System.out: [1] Mutex: false
I/System.out: [2] Mutex: true
I/System.out: [9.594612, 0.60149497, 1.9369502]
I/System.out: [9.562999, -0.49292007, 2.1157124]
I/System.out: [1] Mutex: false
I/System.out: [2] Mutex: true
I/System.out: [9.545794, -0.5383557, 2.1813302]
I/System.out: [9.534273, -0.5199543, 2.235509]

As you see [1] is being printed 2 times without [3] being printed between but with [2] (after the anitLoopMutex = true) between. Why is [1] not printed only 1 time, how to fix it?

1

There are 1 best solutions below

0
On BEST ANSWER

Device rotation recreates the activity. Solution: add android:screenOrientation="portrait" into manifest.