Android sensor overview (1)

Android sensor overview (1)

Most Android devices have built-in sensors that measure motion, screen orientation, and various environmental conditions. These sensors provide highly accurate raw data and are ideal for monitoring the three-dimensional movement or positioning of a device, or monitoring changes in the environment around a device. For example, games can track readings from a device's gravity sensor to infer complex user gestures and movements, such as tilting, shaking, rotating, or waving. Likewise, a weather app could use the device's temperature and humidity sensors to calculate and report dew point, and a travel app could use the geomagnetic field sensor and accelerometer to report compass bearings.

The Android platform supports three broad categories of sensors :

  • Dynamic sensors
    These sensors measure acceleration and rotational forces in three axes. Included in this category are accelerometers, gravity sensors, gyroscopes, and rotation vector sensors.
  • Environmental Sensors
    These sensors measure various environmental parameters such as ambient air temperature, barometric pressure, illuminance, and humidity. This category includes barometers, photometers and thermometers
  • Position Sensors
    These sensors measure the physical position of a device. This category includes screen orientation sensors and magnetometers.

The Android sensor framework can be used to access sensors provided on the device and obtain raw sensor data. The sensor framework provides several classes and interfaces that help you perform various sensor-related tasks. For example, you can use the sensor framework to do the following:

  • Determine which sensors are on the device.
  • Determine the characteristics of individual sensors such as maximum range, manufacturer, power requirements, and resolution.
  • Get raw sensor data and define the minimum frequency for getting sensor data.
  • Register and unregister sensor event listeners for monitoring sensor changes.

Introduction to Sensors

With the Android sensor framework, you can access many types of sensors. Some sensors are hardware based and some are software based. Hardware-based sensors are physical components built into a phone or tablet device. These sensors collect data by directly measuring specific environmental properties, such as acceleration, the strength of the Earth's magnetic field, or changes in angle. Software-based sensors are not physical devices, they just mimic hardware-based sensors. Software-based sensors acquire data from one or more hardware-based sensors and are sometimes called virtual sensors or synthetic sensors. For example, linear acceleration sensors and gravity sensors are software-based sensors.

Few Android devices have all types of sensors. For example, most mobile devices and tablets have accelerometers and magnetometers, but few have barometers or thermometers. Additionally, a device can have multiple sensors of a particular type. For example, a device could have two gravity sensors, each with a different range.

sensor type illustrate common use
TYPE_ACCELEROMETER hardware Measures the acceleration force (including gravity) exerted on the device in all three physical axes (x, y, and z) in m/s2. Motion detection (shaking, tilting, etc.)
TYPE_AMBIENT_TEMPERATURE hardware Ambient room temperature is measured in degrees Celsius (°C). Monitor temperature
TYPE_GRAVITY software/hardware Measures the gravitational force exerted on the device in all three physical axes (x, y, z) in m/s2. Motion detection (shaking, tilting, etc.)
TYPE_GYROSCOPE hardware Measures the rate of rotation of the device in three physical axes (x, y, and z), in rad/s. Rotation detection (rotate, turn, etc.)
TYPE_LIGHT hardware Measures ambient light level (illuminance) in lx Control screen brightness
TYPE_LINEAR_ACCELERATION software/hardware Measures the acceleration force (excluding gravity) applied to the device in all three physical axes (x, y, and z) in m/s2 Monitoring acceleration in a single axis
TYPE_MAGNETIC_FIELD hardware Measures the ambient geomagnetic field in μT on all three physical axes (x, y, z). create a compass
TYPE_ORIENTATION software Measures the rotation of the device around all three physical axes (x, y, z). Beginning with API level 3, you can combine the gravity sensor, the geomagnetic field sensor, and getRotationMatrix()the method to get the tilt and rotation matrices of the device. Determine device location
TYPE_PRESSURE hardware Measures ambient air pressure in hPa or mbar. Monitor air pressure changes
TYPE_PROXIMITY hardware Measures the distance of an object relative to the device's display screen, in cm. This sensor is commonly used to determine if a phone is held up to a person's ear. The location of the phone during a call
TYPE_RELATIVE_HUMIDITY hardware Measures the relative humidity of the environment expressed as a percentage (%). Monitor dew point, absolute and relative humidity
TYPE_ROTATION_VECTOR software/hardware Detects the device's screen orientation by providing three elements of the device's rotation vector Motion Detection and Rotation Detection
TYPE_TEMPERATURE hardware Measures the temperature of the device in degrees Celsius (°C). The implementation of this sensor varies from device to device. In API level 14, this sensor was replaced by TYPE_AMBIENT_TEMPERATUREsensor monitor temperature

sensor frame

The Android sensor framework can be used to access these sensors and obtain the raw data of the sensors. The sensor framework is part of android.hardwarethe package and contains the following classes and interfaces:

  • SensorManager
    Use this class to create an instance of the sensor service. This class provides various methods to access and list sensors, register and unregister sensor event listeners, and obtain screen orientation information. It also provides several sensor constants for reporting sensor accuracy, setting data acquisition frequency, and calibrating sensors.

  • Sensor
    Use this class to create instances of specific sensors. This class provides various methods to determine the characteristics of the sensor.

  • SensorEvent
    Use this class to create sensor event objects that provide information about sensor events. A sensor event object contains the following information: the raw sensor data, the type of sensor that generated the event, the accuracy of the data, and the timestamp of the event.

  • SensorEventListener
    Use this interface to create two callback methods to receive notifications (sensor events) when sensor values ​​or sensor accuracy changes.
    In a typical application, these sensor-related APIs can be used to perform two basic tasks:

    • Identifying Sensors and Sensor Characteristics Identifying sensors and sensor characteristics
      at runtime is useful if your application has functionality that depends on specific sensor types or characteristics. For example, you may want to identify all sensors on a device so that you can disable app functionality that relies on sensors that are not present. Likewise, it may be desirable to identify all sensors of a particular type in order to select the sensor implementation that will bring the best performance to the application.
    • Monitor Sensor Events
      Get raw sensor data by monitoring sensor events. A sensor event occurs whenever a sensor detects a change in the parameter it measures. A sensor event gives you 4 pieces of information: the name of the sensor that triggered the event, the timestamp of the event, the accuracy of the event, and the raw sensor data that triggered the event.

Identify sensors and sensor characteristics

The Android sensor framework provides several methods that allow you to easily determine which sensors are on a device at runtime. The API also provides methods to determine the characteristics of each sensor, such as maximum range, resolution, and power requirements.

To identify a sensor on a device, you first need to obtain a reference to the sensor service. To do this, getSystemService()you SENSOR_SERVICEcreate an instance of SensorManagerthe class . For example:

private SensorManager sensorManager;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    

Next, you can call getSensorList()the method and use TYPE_ALLthe constant to get a list of each sensor on the device. For example:

List<Sensor> deviceSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);    

If you want to list all sensors of a particular type, you can use other constants instead TYPE_ALL, such as TYPE_GYROSCOPE, TYPE_LINEAR_ACCELERATIONor TYPE_GRAVITY.

You can also use getDefaultSensor()the method and pass in a specific sensor's type constant to determine if a sensor of that type exists on the device. If there are multiple sensors of a particular type on a device, one of them must be designated as the default sensor. If no default sensor is specified, the method call returns null, indicating that the device does not have a sensor of that type. For example, the following code checks to see if there is a magnetometer on the device:

private SensorManager sensorManager;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){
    
    
    // Success! There's a magnetometer.
} else {
    
    
    // Failure! No magnetometer.
}

Monitor sensor events

To monitor raw sensor data, you need to implement two callback methods exposed through SensorEventListenerthe interface : onAccuracyChanged()and onSensorChanged(). The Android system calls these two methods when:

  • The sensor's accuracy has changed
    In this case, the system calls onAccuracyChanged()the method , giving you Sensora reference to the changed object and the sensor's new accuracy. Accuracy is represented by one of 4 status constants: SENSOR_STATUS_ACCURACY_LOW, SENSOR_STATUS_ACCURACY_MEDIUM, SENSOR_STATUS_ACCURACY_HIGHor SENSOR_STATUS_UNRELIABLE.
  • A sensor reported a new value
    In this case, onSensorChanged()the method , giving you SensorEventthe object. SensorEventThe object contains information about the new sensor data, including: the accuracy of the data, the sensor that generated the data, the timestamp when the data was generated, and the new data recorded by the sensor.

The following code shows how to use onSensorChanged()the method to monitor the light sensor data. In this example, the raw sensor data is sensor_datadisplayed inmain.xml the defined in the file .TextView

public class SensorActivity extends Activity implements SensorEventListener {
    
    
    private SensorManager sensorManager;
    private Sensor mLight;

    @Override
    public final void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    }

    @Override
    public final void onAccuracyChanged(Sensor sensor, int accuracy) {
    
    
        // Do something here if sensor accuracy changes.
    }

    @Override
    public final void onSensorChanged(SensorEvent event) {
    
    
        // The light sensor returns a single value.
        // Many sensors return 3 values, one for each axis.
        float lux = event.values[0];
        // Do something with this sensor value.
    }

    @Override
    protected void onResume() {
    
    
        super.onResume();
        sensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
    
    
        super.onPause();
        sensorManager.unregisterListener(this);
    }
}

In this example registerListener(), a default data delay ( SENSOR_DELAY_NORMAL) is specified when calling the method. The data latency (or sampling rate) controls the interval at which sensor events are sent to the application via onSensorChanged()the callback method. The default data delay uses a delay of 200,000 microseconds, suitable for monitoring typical screen orientation changes. Other data delays can be specified, such as SENSOR_DELAY_GAME(delay 20,000 microseconds), SENSOR_DELAY_UI(delay 60,000 microseconds), or SENSOR_DELAY_FASTEST(delay 0 microseconds).

Specified delays are suggested delays only. The Android system and other applications can change this delay. It is best practice to specify the largest delay possible, since the system will often use a lower delay than specified (that is, you should choose the lowest sample rate that meets your application's needs). Using a larger latency reduces the load on the processor and thus reduces power consumption.

Once the sample rate (latency) is set, it should not be changed. If for some reason you do need to change the delay, you must unregister and re-register the sensor listener.

Also note that this example uses onResume()the and onPause()callback methods to register and unregister sensor event listeners. As a best practice, always disable sensors you don't need, especially when an activity is paused. Failure to do so could drain the battery within a few hours, as some sensors have high power demands and can drain the battery very quickly. The system does not automatically deactivate sensors when the screen is turned off.

Handle different sensor configurations

Android does not specify a standard sensor configuration for devices, which means that device manufacturers can implement any sensor configuration they want in their Android devices. Accordingly, a device may contain various sensors in various configurations. If your app relies on a particular type of sensor, you must ensure that the sensor is present on the device in order for your app to run successfully.

There are two ways to ensure that a specific sensor is present on a device:

  • Detect sensors at runtime and enable or disable app functionality as needed.
  • Use Google Play filters to target devices with specific sensor configurations.

Detect sensors at runtime

If your app uses a particular type of sensor, but doesn't depend on it, you can use the sensor framework to detect the sensor at runtime and then disable or enable app functionality as needed. For example, a navigation app might use temperature sensors, pressure sensors, GPS sensors, and geomagnetic field sensors to display temperature, barometric pressure, location, and compass bearing. If the device does not have a pressure sensor, you can use the sensor framework to detect the absence of a pressure sensor at runtime and disable the portion of your app's UI that displays pressure. For example, the following code checks to see if a pressure sensor is present on the device:

private SensorManager sensorManager;
...
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null){
    
    
    // Success! There's a pressure sensor.
} else {
    
    
    // Failure! No pressure sensor.
}

Use Google Play Filters to target specific sensor configurations

If you are distributing your application Google Playon , you can use <uses-feature>the element in your manifest file to block your application from devices that do not have the appropriate sensor configuration for your application. <uses-feature>The element has several hardware descriptors that filter applications based on the presence or absence of a particular sensor. Sensors that can be listed include: accelerometer, barometer, compass (terrestrial magnetic field), gyroscope, light sensor, and distance sensor. The following manifest example entry blocks the app for devices without an accelerometer:

<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
    

If you add this element and descriptor to your app's manifest, users will only see the app Google Playon .

Descriptors should only be set to if the app is fully dependent on a particular sensor android:required="true". If your app uses a sensor for some functionality but can function without it, it should list the sensor in <uses-feature>the element but set the descriptor to android:required="false". This ensures that the device can install the app even without the sensor. It's also the best project management method to help keep track of the features your app uses. Remember that if an app uses a particular sensor but can function without it, it should detect the sensor at runtime and disable or enable app functionality as needed.

Sensor coordinate system

Typically, sensor frameworks use a standard 3-axis coordinate system to represent data values. For most sensors, the coordinate system is defined relative to the device screen when the device is in the default screen orientation. When the device is in the default screen orientation, the X axis extends horizontally to the right, the Y axis extends vertically upwards, and the Z axis extends perpendicular to the screen and outwards. In this coordinate system, coordinates behind the screen will have negative Z values. The following sensors use this coordinate system: acceleration sensor, gravity sensor, gyroscope, linear acceleration sensor, geomagnetic field sensor.
insert image description here
One thing to note about this coordinate system is that when the screen orientation of the device changes, the coordinate axes will not be transformed, that is, the coordinate system of the sensor will not change as the device moves. This behavior is identical to that of OpenGLthe coordinate system.

It's also important to note that apps cannot assume that the device's natural (default) orientation is portrait. The natural orientation of many tablet devices is landscape. The sensor coordinate system is always based on the device's natural screen orientation.

Finally, if the application maps sensor data to the screen display, it needs to use getRotation()the method to determine the rotation of the screen, and then use remapCoordinateSystem()the method to map the sensor coordinates to the screen coordinates. This is required even if the manifest specifies portrait only.

Guess you like

Origin blog.csdn.net/tracydragonlxy/article/details/128410934