androidrotationaccelerometerandroid-orientation

How do I stop accelerometer from detecting upward/downward motion when the phone is rotated between portrait-landscape modes


I have 2 booleans up and down for when I move the phone up and down. The default position of the phone is portrait.

When I rotate the phone to landscape, even though I didn't move the phone downwards, the down variable becomes true. Then when I rotate back to portrait, the up value becomes true even if the phone doesn't move up.

How do I stop this from happening? I want it so that if the phone is in up or down mode, it will stay in that mode regardless of the orientation of the phone.

The up-down code:

                if (ty > 3.0f) { // go down
                    getWindow().getDecorView().setBackgroundColor(Color.GREEN);
                    down = true;
                    up = false;
                }
                else if (ty < -3.0f) { // go up
                    getWindow().getDecorView().setBackgroundColor(Color.YELLOW);
                    up = true;
                    down = false;
                }

                upVal.setText("Up: " + up);
                downVal.setText("Down: " + down);

(I also don't know why it turns green when I move it down even though the ty value is positive and vice versa.)

The rotation code:

            if( (orientation < 35 || orientation > 325) && rotation!= ROTATION_O){ // PORTRAIT
                rotation = ROTATION_O;
            }
            else if( orientation > 145 && orientation < 215 && rotation!=ROTATION_180){ // REVERSE PORTRAIT
                rotation = ROTATION_180;
            }
            else if(orientation > 55 && orientation < 125 && rotation!=ROTATION_270){ // REVERSE LANDSCAPE
                rotation = ROTATION_270;
            }
            else if(orientation > 235 && orientation < 305 && rotation!=ROTATION_90){ //LANDSCAPE
                rotation = ROTATION_90;
            }

Solution

  • It turns out all I need to do is to unregister and reregister the accelerometer while the phone is rotating and when it stops respectively.

    1. Add a gyroscope class like here
    2. In MainActivity, add this:
            gyroscope.setListener(new Gyroscope.Listener() {
                // on rotation method of gyroscope
                @Override
                public void onRotation(float rx, float ry, float rz) {
                    if (rz > 1.0f) {
                        //phone is moving, unregister the accelerometer
                        accelerometer.unregister();
    
                    } else if (rz < -1.0f) {
                        // phone is moving, unregister the accelerometer
                        accelerometer.unregister();
    
                    } else {
                        //phone stops moving, re-register the accelerometer
                        accelerometer.register();
                    }
                }
            });