[Android entry to project combat -- 9.1] - sensor usage tutorial

Table of contents

Definition of sensor

Three types of sensors

1. Motion sensor

2. Environmental sensor

3. Position sensor

Sensor Development Framework

1、SensorManager

2、Sensor

3、SensorEvent

4、SensorEventListener

1. Use the sensor development steps

1. Obtain sensor information

1), get the sensor manager

2) Obtain the sensor object list of the device

3) Obtain the Sensor object iteratively, and call the corresponding method to obtain relevant information

2. Obtain the data returned by the sensor

1) Get the sensor manager

2) Call a specific method to obtain the required sensor

3) Implement the SensorEventListener interface and rewrite the onSensorChanged and onAccuracyChanged methods

4) The SensorManager object calls registerListener to register the listener

5) Unregister the listener

2. Example of obtaining sensor information

3. An example of obtaining the data returned by the sensor

principle


        Sensor applications such as the shake function of WeChat, NFC, the compass that comes with the mobile phone, and so on. The following will learn the use of Android sensors.

Definition of sensor

        A physical device or biological organ that can detect and sense external signals, physical conditions (such as light, heat, humidity) or chemical composition (such as smoke), and transmit the detected information to other devices or organs.

Three types of sensors

1. Motion sensor

        – Motion sensors measure acceleration and rotation forces, they include accelerometers, gravity sensors, gyroscopes, and rotation vector sensors.

2. Environmental sensor

        – Environmental sensors measure various surrounding environmental conditions, such as ambient temperature, air pressure, light intensity, humidity, etc. Includes barometer, photometer and thermometer.

3. Position sensor

        – Position sensors measure information about the physical location of a device, including orientation sensors and magnetometers.

Sensor Development Framework

1、SensorManager

        – An instance of the sensor service can be created using this class. This class provides methods to access and list sensors, register and unregister sensor event listeners, and obtain orientation information. This class also provides several sensor constants for reporting the sensor's accuracy, setting the data acquisition rate, and calibrating the sensor.

2、Sensor

        – An instance of a specific sensor can be created using this class. This class provides various methods that allow you to determine the capabilities of a sensor.

3、SensorEvent

        – The system uses this class to create sensor event objects that provide information about sensor events. A sensor event object includes the following information: raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp of the event.

4、SensorEventListener

        – There are two postback methods that can be created using this interface to receive notifications (sensor events) when sensor values ​​change or sensor accuracy changes.

1. Use the sensor development steps

1. Obtain sensor information

        The development of the sensor first needs to obtain some information of the sensor, and the following steps are required to obtain the information:

1), get the sensor manager

        Android provides a sensorManager manager. Through this class, you can get the sensors. The code to get the sensorManager object is as follows:

SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE); 

2) Obtain the sensor object list of the device

        The list of sensor objects can be obtained through the getSensorList() method of the sensorManager manager. The specific code is as follows:

List<Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);

3) Obtain the Sensor object iteratively, and call the corresponding method to obtain relevant information

for(Sensor s:allSensors){
    sensor.getName();   //获得传感器名称
    sensor.getType();     //获得传感器种类
    sensor.getVendor();    //获得传感器供应商
    sensor.getVersion();    //获得传感器版本
    sensor.getResolution();  //获得精度值
    sensor.getMaximumRange(); //获得最大范围
    sensor.getPower();        //传感器使用时的耗电量 
}

2. Obtain the data returned by the sensor

1) Get the sensor manager

SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);

2) Call a specific method to obtain the required sensor

        Call the getDefaultSensor method of the SensorManager object to obtain the specified type of sensor. For example, the light sensor is used here. The specific code:

Sensor mSensorOrientation = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);

3) Implement the SensorEventListener interface and rewrite the onSensorChanged and onAccuracyChanged methods

①: onSensorChanged(SensorEvent event); This method is called when the value of the sensor changes. Its parameter is a SensorEvent object. The value of the sensor can be obtained through the values ​​attribute of the object. The value is an array, and the variable has at most three Elements, and the sensors are different, and the meanings represented by the corresponding elements are also different
②: onAccuracyChanged(Sensor sensor, int accuracy); it will call back when the progress of the sensor changes,
parameter description:
sensor: sensor object
accuracy: indicates the new accuracy of the sensor

@Override
public void onSensorChanged(SensorEvent event) {
     final float[] _Data = event.values;
     this.mService.onSensorChanged(_Data[0],_Data[1],_Data[2]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

4) The SensorManager object calls registerListener to register the listener

        To register the listening event for the sensor, register the listening event by calling the registerListener() method of the sensorManager object.

        The first parameter is the context object, the second is the sensor object, and the third is the precision of the delay time of the sensor. The more precise the more power consumption.

        

  • SENSOR_DELAY_FASTEST - Delay: 0ms
  • SENSOR_DELAY_GAME - delay: 20ms
  • SENSOR_DELAY_UI——Delay time: 60ms
  • SENSOR_DELAY_NORMAL - delay: 200ms

The specific code is as follows:

sm.registerListener(mContext, mSensorOrientation, android.hardware.SensorManager.SENSOR_DELAY_UI);

5) Unregister the listener

sm. unregisterListener(this);

2. Example of obtaining sensor information

        Let’s take the previous first step: get sensor information, and show how to use it with an example.

Create a new project SensorDemo1.

Modify the activity_main.xml code as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/txt_show"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Modify the MainActivity code as follows:

public class MainActivity extends AppCompatActivity {

    private TextView txt_show;
    private SensorManager sm;

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

        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        txt_show = (TextView) findViewById(R.id.txt_show);
        List<Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);
        StringBuilder sb = new StringBuilder();
        sb.append("此手机有" + allSensors.size() + "个传感器,分别有:\n\n");
        for(Sensor s:allSensors){
            switch (s.getType()){
                case Sensor.TYPE_ACCELEROMETER:
                    sb.append(s.getType() + " 加速度传感器(Accelerometer sensor)" + "\n");
                    break;
                case Sensor.TYPE_GYROSCOPE:
                    sb.append(s.getType() + " 陀螺仪传感器(Gyroscope sensor)" + "\n");
                    break;
                case Sensor.TYPE_LIGHT:
                    sb.append(s.getType() + " 光线传感器(Light sensor)" + "\n");
                    break;
                case Sensor.TYPE_MAGNETIC_FIELD:
                    sb.append(s.getType() + " 磁场传感器(Magnetic field sensor)" + "\n");
                    break;
                case Sensor.TYPE_ORIENTATION:
                    sb.append(s.getType() + " 方向传感器(Orientation sensor)" + "\n");
                    break;
                case Sensor.TYPE_PRESSURE:
                    sb.append(s.getType() + " 气压传感器(Pressure sensor)" + "\n");
                    break;
                case Sensor.TYPE_PROXIMITY:
                    sb.append(s.getType() + " 距离传感器(Proximity sensor)" + "\n");
                    break;
                case Sensor.TYPE_TEMPERATURE:
                    sb.append(s.getType() + " 温度传感器(Temperature sensor)" + "\n");
                    break;
                default:
                    sb.append(s.getType() + " 其他传感器" + "\n");
                    break;
            }
            sb.append("设备名称:" + s.getName() + "\n 设备版本:" + s.getVersion() + "\n 供应商:"
                    + s.getVendor() + "\n\n");
        }
        txt_show.setText(sb.toString());
    }
}

The effect is as follows:

 

3. An example of obtaining the data returned by the sensor

           Realize the second step above: obtain the data returned by the sensor, and demonstrate how to use it with an example. The following implements the acquisition of direction sensor data.

principle

 

– The direction of the X axis : from left to right along the horizontal direction of the screen. If the phone is not square, the shorter side needs to be placed horizontally, and the longer side needs to be placed vertically. Value range [-180, 180]
Direction of the Y axis : starting from the lower left corner of the screen and pointing to the top of the screen along the vertical direction of the screen. Value range [-90, 90]
– The direction of the Z axis : when placed horizontally, it points to the direction of the sky. Value range [0, 360]

 

Create a new project SensorDemo2.

Modify the activity_main.xml code as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/tv_value1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="方位角"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_value2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="倾斜角"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_value3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="滚动角"
            android:textSize="18sp"
            android:textStyle="bold" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Modify the MainActivity code as follows:

        

SENSOR_DELAY_FASTEST most sensitive

SENSOR_DELAY_GAME game, but generally this is enough

SENSOR_DELAY_NORMAL is slower.

SENSOR_DELAY_UI slowest

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    private TextView tv_value1;
    private TextView tv_value2;
    private TextView tv_value3;
    private SensorManager sManager;
    private Sensor mSensorOrientation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mSensorOrientation = sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
        bindViews();
    }

    private void bindViews() {
        tv_value1 = (TextView) findViewById(R.id.tv_value1);
        tv_value2 = (TextView) findViewById(R.id.tv_value2);
        tv_value3 = (TextView) findViewById(R.id.tv_value3);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        tv_value1.setText("方位角(沿Z轴):" + (float) (Math.round(event.values[0] * 100)) / 100);
        tv_value2.setText("倾斜角(沿X轴):" + (float) (Math.round(event.values[1] * 100)) / 100);
        tv_value3.setText("滚动角(沿Y轴):" + (float) (Math.round(event.values[2] * 100)) / 100);
    }

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

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sManager.unregisterListener(this);
    }
}

The effect is as follows:

 

In the next article, we will practice the application of the sensor through the two cases of close screen black screen and pedometer.

Guess you like

Origin blog.csdn.net/Tir_zhang/article/details/130515705