Automatic switching between horizontal and vertical screens — Application of mobile phone acceleration sensor in Android horizontal and vertical screen switching

Time:2022-4-1

Author: Huang Longfei, Agora engineer of sound network

preface
When using mobile phones in daily life, we usually encounter the following two scenarios.
Scenario 1:
When using the mobile phone to watch video and the device turns on the screen to rotate automatically, the effect will be different when the mobile phone is held horizontally and vertically. The display in the vertical screen state is shown in the following figure (Figure 1), and the display in the horizontal screen state is shown in Figure 2.

Automatic switching between horizontal and vertical screens -- Application of mobile phone acceleration sensor in Android horizontal and vertical screen switching

Figure 1 Play video on vertical screen

Automatic switching between horizontal and vertical screens -- Application of mobile phone acceleration sensor in Android horizontal and vertical screen switching

Figure 2 Play video horizontally

Scenario 2:
In the mobile applications used, some interfaces of some applications will show different interface effects according to the current horizontal and vertical screen state of the mobile phone, which is convenient for everyone to use. For example, the conference interface in agoravideocall is shown in Figure 3 & Figure 4:

Automatic switching between horizontal and vertical screens -- Application of mobile phone acceleration sensor in Android horizontal and vertical screen switching

Figure 3 Agoravideocall conference interface vertical display

Automatic switching between horizontal and vertical screens -- Application of mobile phone acceleration sensor in Android horizontal and vertical screen switching

Figure 4 Horizontal display of agoravideocall conference interface

Both of the above scenarios automatically identify whether the user wants to display horizontally or vertically according to the way the user holds the mobile phone and the rotation action. about“How can the mobile phone recognize the user’s intention according to the user’s rotation“This issue will be described in detail below.

Principle of acceleration sensor
The core component of the mobile phone to realize this function is the acceleration sensor. Before introducing the acceleration sensor, first understand the sensor coordinate system.

  • Sensor coordinate system

Typically, the sensor frame uses a standard 3-axis coordinate system to represent data values. For most sensors, when the device is in the default screen orientation, the coordinate system is defined relative to the device screen (see Figure 5). When the device is in the default screen direction, the X axis extends horizontally to the right, the Y axis extends vertically upward, and the Z axis extends outward perpendicular to the screen. In this coordinate system, the coordinates behind the screen will have a negative Z value. One thing to note about this coordinate system is that the coordinate system of the sensor will not change with the movement of the equipment.

Automatic switching between horizontal and vertical screens -- Application of mobile phone acceleration sensor in Android horizontal and vertical screen switching

Figure 5 Sensor coordinate system (relative to the device).

  • Acceleration sensor

The acceleration sensor adopts an elastic sensitive element to make a cantilever displacement device, and the energy storage spring made of the elastic sensitive element to drive the electrical contact to complete the conversion from gravity change to electrical signal. For example, a shell and an object to measure acceleration are connected by a spring to form a gravity sensor. When we move the shell upward, the metal ball will stretch the spring downward due to inertia. At this time, we only need to measure the stretching amount of the spring, and we can calculate the gravity from this. Thus, it is easy to obtain that the X, y and Z accelerometers can measure the motion direction of an object in three-dimensional space. For details, seePrinciple of gravity induction]

Application of acceleration sensor in Android horizontal and vertical screen switching
Acceleration sensor has many applications in mobile devices. This paper mainly introduces the application of acceleration sensor in horizontal and vertical screen switching in Android system. Its principle is as follows: by monitoring the acceleration sensor, the acceleration values in X, y and Z directions can be obtained in real time; When 4 (x_x + y_y) > = Z * Z, start to calculate the rotation angle of the equipment on the X and Y planes; Finally, the horizontal and vertical screen state of the equipment is calculated according to the rotation angle. The main codes are posted below.

/**
*In onresume, register the monitoring acceleration sensor with sensormanager
*/
@Override
protected void onResume() {
    super.onResume();
    orientationListener = new OrientationListener(this);
    orientationListener.enable();
}

public void enable() {
    if (mSensor == null) {
        Log.w(TAG, "Cannot detect sensors. Not enabled");
        return;
    }
    if (mEnabled == false) {
        if (localLOGV) Log.d(TAG, "OrientationEventListener enabled");
        mSensorManager.registerListener(mSensorEventListener, mSensor, mRate);
        mEnabled = true;
    }
}

class SensorEventListenerImpl implements SensorEventListener {
    private static final int _DATA_X = 0;
    private static final int _DATA_Y = 1;
    private static final int _DATA_Z = 2;

    /**
    **Calculate the rotation angle of the equipment through the change of acceleration values in X, y and Z directions.
    **/
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        int orientation = ORIENTATION_UNKNOWN;
        float X = -values[_DATA_X];
        float Y = -values[_DATA_Y];
        float Z = -values[_DATA_Z];        
        float magnitude = X*X + Y*Y;
        // Don't trust the angle if the magnitude is small compared to the y value
        if (magnitude * 4 >= Z*Z) {
            float OneEightyOverPi = 57.29577957855f;
            float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
            orientation = 90 - (int)Math.round(angle);
            // normalize to 0 - 359 range
            while (orientation >= 360) {
                orientation -= 360;
            } 
            while (orientation < 0) {
                orientation += 360;
            }
        }
        if (mOldListener != null) {
            mOldListener.onSensorChanged(Sensor.TYPE_ACCELEROMETER, event.values);
        }
        if (orientation != mOrientation) {
            mOrientation = orientation;
            onOrientationChanged(orientation);
        }
    }
}

public class OrientationListener extends OrientationEventListener {
    private int degree = 0;// Rotation angle
    private int mOrientation = 0;// 2 - horizontal screen, 1 - vertical screen, 0 - Unknown
    public OrientationListener(Context context) {
        super(context);
    }
    /**
    *According to the rotation angle, the horizontal and vertical screen state of the equipment can be obtained
    **/
    @Override
    public void onOrientationChanged(int orientation) {
        degree = orientation;
        if (degree > 0 && degree < 45) {
            mOrientation = 1;
        } else if (degree > 45 && degree < 135) {
            mOrientation = 2;
        } else if (degree > 135 && degree < 225) {
            mOrientation = 1;
        } else if (degree > 225 && degree < 315) {
            mOrientation = 2;
        } else if (degree > 315 && degree < 360) {
            mOrientation = 1;
        } 
        if (mOrientation == 2) {
            Log. I ("orientationlistener", "horizontal screen");
        } else if (mOrientation == 1) {
            Log. I ("orientationlistener", "vertical screen");
        }
    }
}

Special note: math Atan2 (- y, x) is the plane angle (radian value) between the line segment from the origin (0,0) to the point (x, y) and the positive direction of the X axis,
float angle = (float)Math. Atan2 (- y, x) * oneeightyoverpi gets the angle between the line segment from the origin (0,0) to the point (x, y) and the positive direction of the X axis, 90 – (int) math Round (angle) is the rotation angle of the equipment.

Actual combat drill
This section implements a simple golf game to practice the application of acceleration sensor. The game is a multiplayer game. The rules of the game are: Participants control the movement of the golf ball by shaking their mobile phone. When the golf ball falls into the hole, 1 point will be counted, otherwise no point will be counted. Each person operates for 3 times, and the person with the highest score will win. The implementation principle of the game is to obtain the rotation angle of the equipment according to the acceleration sensor, calculate and update the position of the golf ball in real time, and judge whether the golf ball falls into the hole according to the coincidence degree between the position of the golf ball and the hole. If you fall into the hole, you will get a score, otherwise, you will not get a score. See the attachment for the specific implementation of the game, and the demonstration is as follows.

Link:https://pan.baidu.com/s/1Kas3kL0fdaXbygGA–l7JQ 2Extraction code: 87nh
Link:https://pan.baidu.com/s/1yXNbbI3QhYG3BMZsyG2PSw 1Extraction code: 8uaz

extend
In addition to the acceleration sensors described above, most mobile devices also have many built-in sensors, such as gravity sensor, rotation vector sensor, screen direction sensor, temperature sensor, light sensor, pressure sensor, etc. (for details, please refer tosensor)。 According to these sensors, developers can realize many very intelligent functions. For example:

  • Through the light sensor, the brightness of the screen is automatically adjusted to protect the user’s eyes
  • Through the acceleration sensor, the pedometer and motion detection function are realized
  • Calculate dew point and absolute humidity through humidity sensor and temperature sensor
  • The navigation function is realized through GPS

reference:

enclosure
AccelerometerPlay.zip (5.0 KB)