This article describes the sensors in your Android device.
Sensor Overview (Sensors overview)
Most Android devices have a large number of sensors built into them, which are more common in measuring displacements, sensing directions, sensing ambient changes, and so on. These sensors are able to feed back high-precision raw data, and can monitor the displacement of the device in three directions and changes in the surrounding environment. For example, in a weather application you can use a temperature sensor and a humidity sensor to get a change in the surrounding environment, and you can use geomagnetic sensors and accelerators to set the compass direction in a travel application.
Android devices offer three types of sensors:
Motion sensors: This type of sensor monitors the acceleration and rotational forces of the device in the direction of the three axes (measure acceleration forces and rotational forces along three Axes). Mainly include: accelerometer (accelerometers), gravity sensor (gravity sensors), gyroscope (gyroscopes) and rotation vector sensor (rotational vector sensors) and so on.
Environmental sensors (environmental sensors): These sensors can monitor the environmental parameters of the device, such as temperature, barometric pressure, brightness, humidity, etc. (measure various environmental parameters, such as Ambient air temperature and pressure, illumination, and humidity). Mainly include: barometer (barometers), photometer (photometers), thermometer (thermometers) and so on.
Position sensor (Position sensors): This type of sensor can monitor the physical location of the device. such as direction sensor and magnetometer (orientation sensors and magnetometers).
Using the APIs in Android, you can easily get the raw data detected by various sensors. For example, you can do the following with these APIs:
The number and type of sensors contained in the current device;
Parameters for each sensor. such as the maximum measurable, manufacturer, required power, measurement accuracy, etc. (maximum range, manufacturer, power requirements, and resolution).
The interval (frequency) at which data is obtained from the sensor.
When the state of the sensor changes, it can be monitored by registering the listener.
Sensor Introduction (Introduction to sensors)
From the bottom drive division, the sensor can also be divided into hardware-driven and software-driven. Hardware-driven sensors (hardware-based sensors) are real physical parts embedded in Android devices. These physical components can detect ambient properties by themselves and output measurement data such as acceleration, geomagnetic field strength, and angle variations. Although the soft-drive sensor (software-based sensors) looks similar to a hardware-driven sensor, the former is not a physical component. Software-driven sensors typically provide data that is calculated and synthesized from the output of several different types of hardware-driven sensors, so they are sometimes referred to as virtual sensors or synthetic sensors (virtual sensors or synthetic sensors). Linear accelerators and gravity sensors are soft drive sensors. The table below gives a brief introduction to the various Android sensors.
In one device, there may be more than one sensor of the same type. For example, a device contains two gravity sensors, each measuring a different range.
| Sensors (sensor) |
types (type) |
description (Description) |
Application Scenario (Common Uses) |
Acceleration meterTYPE_ACCELEROMETER |
Hardware-driven |
You can monitor the acceleration of the device in the direction of the three axes in a three-dimensional coordinate system, in m/s^2, and of course the magnitude of the gravitational acceleration (g). |
Monitor the movement of equipment, such as shaking, tilting and so on. |
ThermometerTYPE_AMBIENT_TEMPERATURE |
Hardware-driven |
Monitors the temperature of the current device environment, in degrees Celsius (°c). |
Monitor temperature changes |
Monitoring of gravitational accelerationTYPE_GRAVITY |
Software-driven, hardware-driven |
You can monitor the acceleration of the device in the direction of the three axes in a three-dimensional coordinate system, in m/s^2 |
Monitor the movement of equipment, such as shaking, tilting and so on. |
GyroscopeTYPE_GYROSCOPE |
Hardware-driven |
Monitor the angular velocity of the device in the direction of the three axes, in rad/s |
Detection of rotation or reversal of equipment (spin, turn) |
Light sensorTYPE_LIGHT |
Hardware-driven |
Monitor the light intensity of the environment in which the device is located, in Lux (LX) |
Control the brightness of the screen |
Linear acceleratorsTYPE_LINEAR_ACCELERATION |
Software-driven, hardware-driven |
You can monitor the acceleration of the device in the direction of the three axes in a three-dimensional coordinate system, in m/s^2, and of course the magnitude of the gravitational acceleration (g). |
Monitoring the acceleration of a device in a certain direction |
Measuring magnetic field strengthTYPE_MAGNETIC_FIELD |
Hardware-driven |
The magnetic field strength of the monitoring device in the direction of the three axes is micro-Tesla (μt) |
Implementing the Compass function |
Measurement directionTYPE_ORIENTATION |
Software-driven |
The angle between the monitoring device and the three coordinate planes; Call getRotationMatrix() method to get the rotation matrix of the device. |
Determine the location of the equipment. |
Monitoring air pressureTYPE_PRESSURE |
Hardware-driven |
The air pressure in the environment where the equipment is monitored, in kpa (hPa) or mbar (mbar), where the 1000hpa=1000hpa=1 is strong |
Monitor the change of atmospheric pressure. |
Measuring distanceTYPE_PROXIMITY |
Hardware-driven |
A straight-line distance between an object and a device screen, typically used to monitor the distance between the phone screen and the user's ear when making a phone call |
Distance from the phone screen of the ear |
Relative humidityTYPE_RELATIVE_HUMIDITY |
Hardware-driven |
Relative humidity measurement of air (%) |
It is used to monitor the temperature (also called dew point) of the condensation when the water vapor is saturated and the temperature of the humid air in the atmosphere drops. Also used to monitor absolute humidity, relative humidity |
Rotation vectorTYPE_ROTATION_VECTOR |
Software-driven, hardware-driven |
Rotation vector of the monitoring device in the direction of three axes |
Monitoring the movement and rotation of equipment |
Measuring temperatureTYPE_TEMPERATURE |
Hardware-driven |
The temperature at which the device is located is in degrees Celsius (°c), which replaces the old sensor in API 14 and later TYPE_AMBIENT_TEMPERATURE |
Monitoring temperature |
Sensor frame (Sensors framework)
You can get these sensor instances and the monitoring parameters returned through the Android sensor framework. These are the classes or interfaces that are described in the android.hardware package.
SensorManager: You can get an instance of the sensor service through this class. This class provides a way to get different kinds of sensor instances, how to bind and unbind the monitor sensor, and how to get the device facing parameters (this class provides various methods for accessing and listing sensors , registering and Unregistering sensor event listeners, and acquiring orientation information). The class also provides a number of static constants to control the sensor's monitoring accuracy and frequency of return data, as well as the calibration method (this class also provides several sensor constants that is used to the report sensor accuracy, set data acquisition rates, and calibrate sensors).
Sensor: A specified sensor instance can be obtained by this class. With this example, you can invoke a number of methods to manipulate the sensor.
SensorEvent: Through this class, you can create an instance of a sensor event that contains information such as the sensor's raw data, the type of sensor event generated, the accuracy of the data, the timestamp of the event (the raw sensor data, the type of Generated the event, the accuracy of the data, and the timestamp for the event).
SensorEventListener: This callback interface contains two methods that are used to receive notifications returned by sensor events when the parameters or accuracy of the sensor monitor change.
The typical way to use the above API in your application is:
Determine the type of sensor and the function of the sensor (identifying sensors and sensor capabilities): If in your application, a feature needs to be implemented through specific features of a specific sensor, It is necessary to test the sensor in the device and find the appropriate type and use its specific functions.
Monitor sensor events: monitor sensor events, that is, how to obtain the original sensor data. When the monitoring data is changed, the sensor event will return the latest data. The data contains four parts: the name of the sensor that triggered the event, the timestamp of the event, the accuracy of the event, and the original data for the departure event (the name of the triggered the event, the timestamp for the even T, the accuracy of the event, and the raw sensor data that triggered the event).
Sensors availability (sensor availability)
Different devices and different versions of Android have different sensors. These sensors are the sensors available in Android 4.0 and later (some are obsolete but still available):
TYPE_ACCELEROMETER;
TYPE_AMBIENT_TEMPERATURE;
TYPE_GRAVITY;
TYPE_GYROSCOPE;
TYPE_LIGHT;
TYPE_LINEAR_ACCELERATION;
TYPE_MAGNETIC_FIELD;
TYPE_ORIENTATION(obsolete but still available);
TYPE_PRESSURE;
TYPE_PROXIMITY;
TYPE_RELATIVE_HUMIDITY;
TYPE_ROTATION_VECTOR;
TYPE_TEMPERATURE(deprecated but still available).
Determine the type of sensor and the function of the transducer (identifying sensors and sensor capabilities)
SensorManagerhere's how to get an instance:
private SensorManager mSensorManager;...mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Get the list of all sensors in the current device in the following way:
List<Sensor> deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
If you need to get a list of all sensors of a particular type, you need to TYPE_ALL replace the constants with:
Sensor.TYPE_GYROSCOPE: This means that you need to get a list of all the sensors with gyroscope capability;
Sensor.TYPE_LINEAR_ACCELERATION: This means that you need to get a list of all the sensors with linear accelerator capabilities;
Sensor.TYPE_GRAVITY: This means that you need to get a list of all the sensors with the gravity meter function;
You can also call a getDefaultSensor() method to determine whether the device has a specified type of sensor, and if there is at least one, then the method will not return NULL, otherwise it will return null as follows:
private SensorManager mSensorManager;...mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){ // 设备中至少内置了一个磁力计 }else { // 设备中没有内置磁力计 }
In addition, by invoking the Sersor public method in the class, you can also set parameters for the specified sensor to determine its properties. For example, the invocation getResolution() and getMaximumRange() method can obtain the frequency and measurement range of the sensor's return raw data separately. getPower()the calling method can obtain the rated power of the sensor's work.
By invoking the Sensor class's getVendor() and getVersion() methods, you can obtain the specified manufacturer and the specified version of the sensor in the device. If you need to monitor the user's tilt or shake gestures (tilt and shake), then you need to use a gravity meter, and the following example shows "in all gravity gauges in the device, get a gravity meter sensor with a version of 3 for Google Inc., the manufacturer. If the device does not have a sensor that satisfies this condition, then it is replaced with an accelerator, if the accelerator is not, then the function of monitoring user gestures will not be realized.
PrivateSensormanager Msensormanager;PrivateSensor Msensor;...msensormanager = (sensormanager) getsystemservice (context.sensor_service); mSensor =NULL;if(Msensormanager.getdefaultsensor (sensor.type_gravity)! =NULL) {list<sensor> gravsensors = msensormanager.getsensorlist (sensor.type_gravity); for(intI=0; I<gravsensors.size (); i++) {if(Gravsensors.Get(i). Getvendor (). Contains ("Google Inc.")) && (gravsensors.Get(i). GetVersion () = =3)){//Use the version 3 gravity sensor.Msensor = gravsensors.Get(i); } }}if(Msensor = =NULL){//Use the accelerometer. if(Msensormanager.getdefaultsensor (sensor.type_accelerometer)! =NULL) {msensor = Msensormanager.getdefaultsensor (Sensor.type_accelerometer); }Else{//Sorry, there is no accelerometers on your device. //You can ' t play this game.}}
There are also practical ways to getMinDelay() return an integer in microseconds (microseconds), which indicates the interval at which the sensor returns the original data, and if the value returned is not 0, this is a flow sensor (streaming sensor), The flow sensor says that the sensor is returning data at this interval, regardless of whether the original monitoring data returned by the sensor has changed. Conversely, if 0 is returned, indicating that it getMinDelay() is not a flow sensor, the non-flow sensor indicates that the sensor only returns data when the monitored data has changed.
Monitoring sensor events (monitoring sensor event)
In order to listen to the original data returned by the sensor, you need to implement SensorEventListener the two callback methods in the interface: onAccuracyChanged() 和 onSensorChanged() . The system will callback both methods when the following events occur:
When the accuracy of the sensor changes (a-sensor's accuracy changes): In this case, a onAccuracyChanged() callback is made and a reference to the Sensor class object is returned to adjust the sensor's accuracy. Accuracy is divided into four levels:,,, SENSOR_STATUS_ACCURACY_LOW SENSOR_STATUS_ACCURACY_MEDIUM SENSOR_STATUS_ACCURACY_HIGH SENSOR_STATUS_UNRELIABLE .
When the sensor recalls the new raw data (a-sensor reports a new value): At this point, it onSensorChanged() is called back. and callbacks a SensorEvent reference to a class object that contains the latest raw data, including: the accuracy of the data, the sensor that generated the data, the timestamp of the data produced, the new data, and so on (the accuracy of the the data, the sensor that generated th e data, the timestamp at which the data is generated, and the new data that the sensor recorded).
The following shows the raw data for listening to the light sensor and displays the data on the TextView:
Public class sensoractivity extends Activity implements Sensoreventlistener { PrivateSensormanager Msensormanager;PrivateSensor Mlight;@Override Public Final void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main); Msensormanager = (Sensormanager) getsystemservice (Context.sensor_service); Mlight = Msensormanager.getdefaultsensor (sensor.type_light); }@Override Public Final void onaccuracychanged(Sensor sensor,intAccuracy) {//do something here if sensor accuracy changes.}@Override Public Final void onsensorchanged(Sensorevent event) {//The light sensor is returns a single value. //Many sensors return 3 values, one for each axis. floatLux = event.values[0];//Do something with the This sensor value.}@Override protected void Onresume() {Super. Onresume (); Msensormanager.registerlistener ( This, Mlight, Sensormanager.sensor_delay_normal); }@Override protected void OnPause() {Super. OnPause (); Msensormanager.unregisterlistener ( This); }}
registerListener()the third parameter of the method represents the frequency of the specified sensor's postback data, which SENSOR_DELAY_NORMAL indicates the frequency of the postback data is 200,000 microseconds (
0.2 seconds), and other constants SENSOR_DELAY_GAME , which represent a 20,000 microsecond interval (
0.02 seconds) SENSOR_DELAY_UI , which represents the interval of 60,000 microseconds (0.06 seconds) SENSOR_DELAY_FASTEST , which represents the fastest.
Use Google Play to filter devices that do not contain a specific sensor (using Google Play filters to target specific sensor configurations)
Configuring a label in Mainfest.xml <uses-feature> indicates that your app requires a specified sensor to run, and if a device doesn't carry the sensor you specify, your app won't appear in the Google Play store that the device is logged into. Like what:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
The <uses-feature> accelerator is configured in the label and the android:required property is set to true, which means that your app will be completely dependent on the accelerometer sensor to run, and if the device does not contain an accelerometer, you will not be able to search for the app when you use the device to access Google Play; android:required property to False, which means that some features of the app require an accelerometer, but the entire app is not dependent on the accelerometer, in which case you can still search for the app in the store, but the part of the feature that needs to use the accelerometer is not available.
coordinate system of sensors (sensor coordinate system)
The coordinates of the sensor in Android are as follows:
Note that the default orientation of the phone is vertical, that is, when the Y axis is vertical, and the default orientation of the tablet is horizontal, and the Y axis is vertical (perpendicular to the wide edge).
Considerations for using sensors (best practices for accessing and using sensors)
- Log off the sensor when not in use (preferably in OnPause ()), or drain the battery (Unregister sensor listeners,if A sensor listener is registered and its activity I S paused, the sensor would continue to acquire data and use battery resources unless you unregister the sensor):
private SensorManager mSensorManager; ...@Overrideprotected void onPause() { super.onPause(); mSensorManager.unregisterListener(this);}
Do not test the sensor on the simulator (Don ' t test your code on the emulator);
Do not onSensorChanged() do a lot of work in the method (Don ' t block the onsensorchanged () onSensorChanged() method): Methods need to continue to return data at a higher frequency, so do not block the method;
Avoid using deprecated methods and constants (Avoid using deprecated methods or sensor types): TYPE_ORIENTATION This type of sensor has been discarded, the method should be called to get directions, and getOrientation() the TYPE_TEMPERATURE constant has been deprecated, you should use the TYPE_AMBIENT_TEMPERATUREconstant substitution.
Be sure to verify before using the sensor (Verify sensors before you use them): Any sensor is not readily available and requires you to instantiate it yourself;
Carefully set the return frequency of the sensor data (Choose sensor delays carefully): when the frequency is high, the power consumption is compared.
Location and Sensors APIs (middle) of the official Android document