Sensors in Android

The Android system provides support for sensors. If the mobile phone hardware provides these sensors, the Android application can obtain the external conditions of the device through the sensors, including the operating status of the mobile phone, external magnetic field, temperature and pressure, etc. The Android system provides drivers to manage these sensor hardware. For developers, they only need to register a listener for the specified sensor.

Android commonly used sensors

1 orientation sensor

It is used to sense the placement status of the mobile phone device. The direction sensor can return three angles, and these three angles can determine the placement status of the mobile phone.

The first angle: the angle between the top of the phone and true north when the phone is placed flat on the table. The phone rotates around the Z axis, and the angle value changes. If the top faces due north, the angle is 0°, and if the top of the phone faces due east, it is 90°

The second angle: the angle at which the top or tail of the mobile phone is tilted. The rotation angle of the mobile phone around the X axis changes. The screen of the mobile phone is 0° upward, lift it from the top of the mobile phone, rotate the mobile phone along the X axis until the screen of the mobile phone is downward, the angle value will be from 0° to -180°, if it is lifted along the bottom of the mobile phone, move the mobile phone along the X axis Axis rotation until the phone screen is down, the angle value will be from 0° to +180°.

The third angle: the angle at which the left or right side of the mobile phone is tilted, and the angle value of the mobile phone around the Y axis will change. Place the phone horizontally, lift it from the left side until the phone is vertical to the table, the angle is from 0° to -90°, and lift it from the right side, the angle is from 0° to 90°.

2 Gyro sensors:

It is used to sense the rotation speed of the mobile phone device. It can return the rotation speed of the device around the three coordinate axes of XYZ. The unit of rotation is (rad/s). The positive value of the rotation speed represents counterclockwise, and the negative value of the rotation speed represents clockwise.

The first value represents the angular velocity of rotation around the X axis, the second value represents the angular velocity of rotation around the Y axis, and the third value represents the angular velocity of rotation around the Z axis.

3 Magnetic field sensor

It is used to read the strength of the magnetic field outside the mobile phone device. The mobile phone device is always in the earth's magnetic field. With the different placement of the mobile phone, the influence of the surrounding magnetic field on the XYZ direction of the mobile phone will change. The three data returned by the magnetic field sensor are from the magnetic field in the XYZ direction, and the unit is "micro Tesla".

4 gravity sensor

A three-dimensional vector will be returned. This three-dimensional vector can show the direction and strength of gravity. The coordinate system of the gravity sensor and the coordinate system of the acceleration sensor are the same.

5 Linear Acceleration Sensor

Returns a three-bit vector showing the acceleration in each direction of the device.

Acceleration sensor = gravity sensor + linear acceleration sensor

6 temperature sensor

Obtain the ambient temperature of the mobile device, and return a data representing the temperature of the mobile phone, in degrees Celsius.

7 light sensor

Used to obtain the light intensity of the environment where the mobile device is located, and return a data representing the surrounding light intensity, the unit is lux (lux)

8 temperature and humidity sensor

It is used to obtain the humidity of the environment where the mobile device is located, and returns a percentage representing the air humidity in the environment

9 pressure sensor

Used to obtain the environmental pressure of the mobile device, the pressure sensor will return a data representing the pressure around the device

10 Heart rate sensor

It can return the wearer's heartbeat per minute, and the accuracy of the data returned by the sensor can be judged by the accuracy of SensorEvent. The heart rate sensor requires the android.permission.BODY_SENSORS permission.

The steps to develop a sensor application are as follows:

1 Call Context's getSystemService(Context.SENSOR_SERVICE) to get the sensorManager object

2 Call the getDefaultSensor() method of sensorManager to get the specified sensor type

3 Usually, in the onResume method of the Activity, the registerListener() method of the sensorManager is called to register the listener for the specified sensor, and the program can obtain the data returned by the sensor by implementing the listener

There are three parameters in registerListener, described as follows:

1 listener: Need to implement the interface of SensorEventListener

2 sensor: sensor object

3 samplingPeriodUs: Get the data frequency of the sensor

SENSOR_DELAY_FASTEST: The fastest delay is the smallest, and the power consumption is fast. Generally, applications that rely on sensor data will adopt this frequency

SENSOR_DELAY_GAME: A frequency suitable for games, generally used for real-time requirements

SENSOR_DELAY_NORMAL: Normal frequency, suitable for applications that do not require high real-time performance

SENSOR_DELAY_UI: The frequency suitable for ordinary user interface, with large delay and low overhead, suitable for use in small programs.

Example:

code:

public class MainActivity extends AppCompatActivity implements SensorEventListener {
    SensorManager sensorManager;
    private TextView textView
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);
        sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);//①
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor defaultSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//②
        sensorManager.registerListener(this, defaultSensor,//③
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);//取消注册
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        String res="X方向上的速度:"+values[0]+"\nY方向上的速度:"+values[1]+"\nZ方向上的速度:"+values[2];
        textView.setText(res);
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}

Result: You can see the acceleration value returned by the mobile phone sensor when you are holding the mobile phone.

Compass app:

Find a picture of a compass, and rotate the picture of the compass in the opposite direction according to the angle with the direction of true north.

public class NorthActivity extends AppCompatActivity implements SensorEventListener {
    ImageView northImg;
    SensorManager mSensorManager;

    float currentDegree = 0f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_north);
        northImg = findViewById(R.id.north_img);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
    }
    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        int senorType = event.sensor.getType();
        switch (senorType) {
            //获取绕Z转过的角度
            case Sensor.TYPE_ORIENTATION:
                float degree = event.values[0];
                //创建反转动画
                RotateAnimation ra = new RotateAnimation(currentDegree, -degree,
                        Animation.RELATIVE_TO_SELF, 0.5f,
                        Animation.RELATIVE_TO_SELF, 0.5f);
                //设置动画持续时长
                ra.setDuration(200);
                //运行动画
                northImg.startAnimation(ra);
                currentDegree=-degree;
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}

Renderings:

Guess you like

Origin blog.csdn.net/m0_56366502/article/details/129166472