1. Related introduction to sensors:

Speaking of sensors, I believe everyone is familiar with them. For example, WeChat's "Shake" feature uses an accelerometer sensor;

Definition of a 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!

Types of sensors:: Sensors can be classified from different perspectives: conversion principle (the basic physical or chemical effect by which the sensor works); purpose; output signal; and manufacturing materials and processes, etc. Generally, they are divided by working principle into two categories: physical sensors and chemical sensors! The ones on mobile phones are basically all physical sensors. The sensors on mobile phones include the following:

  • Orientation sensor
  • Accelerometer sensor
  • Gyroscope sensor
  • Magnetic field sensor
  • Proximity sensor
  • Light sensor
  • Pressure sensor
  • Temperature sensor
  • Gravity sensor (introduced in Android 2.3)
  • Linear acceleration sensor (introduced in Android 2.3)
  • Rotation vector sensor (Android 2.3)
  • Relative humidity sensor (Android 4.0)
  • Near-field communication (NFC) sensor (introduced in Android 2.3). Unlike others, NFC has read and write functions.

Of course, besides these, there are others such as heart rate sensors, step sensors, fingerprint sensors, etc. For the types of sensors supported by Android devices, please refer to the official documentation:SensorThe content in the Summary section~


2. How to check what sensors your phone supports?

Certainly not all phones have all the types mentioned above. The types and number of sensors on each phone may be different. For example, the Nexus 5 I have supports the following sensor types: gravity, light, proximity, pressure, and gyroscope! While the Moto X (2nd gen) I have has gravity, light, proximity, and infrared sensors! As for the sensor types supported by your phone, you can go to relevant review websites such as ZOL Mobile Online, PConline, etc., search for your model, and check the relevant parameters! Of course, we can also write code ourselves to see what sensor types our phones support~

Code example:

Running effect screenshot:

Code implementation:

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <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>
</RelativeLayout>

MainActivity.java:

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());
    }
}

3. Sensor-related methods and usage patterns

From the example in 2, we can roughly summarize the process of obtaining a Sensor and some sensor-related information as follows:

1) Related methods of Sensor

Step 1: Obtain the sensor manager:

SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE); 
  • Step 2: Obtain the list of the device's sensor objects:
List<Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);
  • Step 3: Iterate to obtain Sensor objects, and then call the corresponding methods to get the sensor-related information:
for(Sensor s:allSensors){
    sensor.getName();   //获得传感器名称
    sensor.getType();     //获得传感器种类
    sensor.getVendor();    //获得传感器供应商
    sensor.getVersion();    //获得传感器版本
    sensor.getResolution();  //获得精度值
    sensor.getMaximumRange(); //获得最大范围
    sensor.getPower();        //传感器使用时的耗电量 
}

2) Sensor usage patterns

Generally, we rarely directly obtain a Sensor just to get the above information! Because it is not of much use. More often, we obtain the data collected by the sensor, such as the current atmospheric pressure, the three angle values of the orientation sensor, or the values of the gyroscope~ And most sensor data collection follows the pattern below:

~Step 1: Obtain the sensor manager:

SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE); 

~Step 2: Call a specific method to obtain the desired sensor:

For example, here we obtain the orientation sensor. Whatever sensor you want to obtain, check the API yourself~:

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

~Step 3: Implement the SensorEventListener interface and override the onSensorChanged and onAccuracyChanged methods!

onSensorChanged: It will be called back when the sensor's value changes

onAccuracyChanged: It will be called back when the sensor's accuracy changes

@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) {
}

The general source from which we obtain sensor data is this SensorEvent. This class has avariable called "values",, the type isFloat[], this variablehas at most only three elements,, and different sensors have different meanings for the corresponding elements. For example, in the orientation sensor, the first element is the azimuth value, while in the pressure sensor, the first value is the atmospheric pressure value!

~Step 4: The SensorManager object calls registerListener to register the listener:

<code>ms.registerListener(mContext, mSensorOrientation, android.hardware.SensorManager.SENSOR_DELAY_UI);
</code>

The method is also very simple. The corresponding parameters are:Context object,Sensor object, andthe precision density of the sensor's delay timeThere are four optional values:

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

Of course, lower delay means more frequent detection, and also more battery consumption. If you don't require very high accuracy, it is recommended not to use too high a precision. Generally, the third one is used more often~ Weigh it yourself~

~Step 5: Unregister the listener:

Releasing it after use is a good habit. Generally, we can write it in the destroy method of an Activity or Service:

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

Alright, the pattern is very simple~


4. Download the sample code for this section:

SensorDemo1.zip


Summary of this section:

Alright, in this section we introduced sensors in Android and how to know which sensors your phone supports. Besides searching online, you can also write code to test. Then we also explained the method flow for obtaining Sensor-related information. Finally, we also explained the pattern for collecting sensor data. Later, we will analyze the usage of some commonly used sensors. Stay tuned~