Below are several constants that represent sensor defined in the API.
Int | TYPE_ACCELEROMETER | A constant describing an accelerometer sensor type. Acceleration sensor |
int | TYPE_ALL | A constant describing all sensor types. All types A constant describing all sensor types. |
int | TYPE_GRAVITY | A constant describing a gravity sensor type. |
int | TYPE_GYROSCOPE | A constant describing a gyroscope sensor type Swivel sensor |
int | TYPE_LIGHT | A constant describing an light sensor type.Light sensor |
int | TYPE_LINEAR_ACCELERATION | A constant describing a linear acceleration sensor type. |
int | TYPE_MAGNETIC_FIELD | A constant describing a magnetic field sensor type.Magnetic field sensor |
int | TYPE_ORIENTATION |
This constant is deprecated. use () instead. |
int | TYPE_PRESSURE | A constant describing a pressure sensor type pressure gaugesensor |
int | TYPE_PROXIMITY | A constant describing an proximity sensor type.Distance sensor |
int | TYPE_ROTATION_VECTOR | A constant describing a rotation vector sensor type. |
int | TYPE_TEMPERATURE | A constant describing a temperature sensor type Temperature sensor |
When writing sensor-related code, we can follow the following steps:
Step 1: Obtain the Sensor Manager
SensorManger sm = (SensorManager).getSystemService(SENSOR_SERVICE);
Step 2: Register the monitor for the specific sensor. Here we use the magnetoresistive sensor Sensor.TYPE_ORIENTATION.
sm,registerListener (this,(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
If you want to register other sensors here, you can change the sensor type attribute of the first parameter value. We should register based on the actual sensors in the phone. If in the phone
There is no sensor we registered, and even if we register, it will not work.
The third parameter value indicates the speed of obtaining sensor data. SENSOR_DELAY_FASTEST indicates the acquisition of sensor data as quickly as possible. In addition to this value, 3 acquisitions can be set.
The speed values of sensor data, these values are as follows:
SENSOR_DELAY_GAME If you use sensors to develop games, it is recommended to use this value. Generally, most games with higher real-time use this level.
SENSOR_DELAY_NORMAL The default speed of obtaining sensor data. Standard delay can be used for general puzzle games or EASY games, but too low sampling rate may cause frame skipping for some racing games.
SENSOR_DELAY_UI If you use the sensor to update the UI, it is recommended to use this value.
SENSOR_DELAY_FASTEST: The minimum latency is generally not particularly sensitive to processing. This mode may cause a large amount of power consumption of the mobile phone. Moreover, since the transferred large amount of raw data, poor algorithm processing will affect the performance of the game logic and UI.
The third step is that we have set up monitoring for the sensor in the second part. We need to implement specific monitoring methods. In Android, applications use sensors mainly rely on the interface. This interface can monitor various events of the sensor. The SensorEventListener interface code is as follows:
public interface SensorEventListener {
public void onSensorChanged(SensorEvent event) {
}
public void onAccuracyChanged(Sensor sensor ,int accuracy ){
}
}
When the sensor's value changes, for example, when the magnetoresistive sensor direction changes, OnSensorChanged() is called. When the sensor's accuracy changes, OnAccuracyChanged() method is called.
First, we can take a look at the comments and example codes in the android development document:
public class SensorActivity extends Activity, implements SensorEventListener { private final SensorManager mSensorManager; private final Sensor mAccelerometer; public SensorActivity() { mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); mAccelerometer = (Sensor.TYPE_ACCELEROMETER); } protected void onResume() { (); (this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } protected void onPause() { (); (this); } public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { } }
Always make sure to disable sensors you don't need, especially when your activity is paused. Failing to do so can drain the battery in just a few hours. Note that the system will not disable sensors automatically when the screen turns off.
As you can see, the document requires that the sensors we do not need should be unregistered as much as possible, especially when our activity is in a state of losing focus. If we don't do the above, the battery of the mobile phone will be used up very quickly.
It should also be noted that when the screen is turned off, the sensor will not automatically unregister.
So we can use the onPause() method and onresume() method in the activity. Register the listener for the sensor in onresume method i, in onPause()
Unregister in the method.
The following is a simple DEMO written using the direction sensor
public class SensorActivity extends Activity, implements SensorEventListener { private final SensorManager mSensorManager; private final Sensor mAccelerometer; public SensorActivity() { mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); mAccelerometer = (Sensor.TYPE_ACCELEROMETER); } protected void onResume() { (); (this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } protected void onPause() { (); (this); } public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { } } package ; import ; import ; import ; import ; import ; import ; import ; public class OrientationSensorTest extends Activity implements SensorEventListener { private SensorManager sensorManager = null; private Sensor orientaionSensor = null; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(); setTitle("Direction Sensor DEMO"); textView = (TextView) findViewById(); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); orientaionSensor = sensorManager .getDefaultSensor(Sensor.TYPE_ORIENTATION); } @Override protected void onPause() { (); (this); // Unregister the listener } @Override protected void onResume() { (); (this, orientaionSensor, SensorManager.SENSOR_DELAY_NORMAL); //Register listener for sensor } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { float x = [SensorManager.DATA_X]; float y = [SensorManager.DATA_Y]; float z = [SensorManager.DATA_Z]; ("x=" + (int) x + "," + "y=" + (int) y + "," + "z=" + (int) z); } }
The following describes how the coordinate system of Android defines the x, y z axes.
The direction of the x-axis is from left to right along the horizontal direction of the screen. If the phone is not a square, the shorter sides need to be placed horizontally and the longer sides need to be placed vertically.
The Y-axis direction starts from the lower left corner of the screen and points to the top of the screen along the vertical direction of the screen.
Place your phone on the table, and the z-axis direction is from the phone to the sky.
Since Apple released the first generation of iPhones in 2007, sensors that seemed to be out of touch with mobile phones have gradually become an important part of mobile phone hardware. If readers have used iPhone, HTC Dream, HTC Magic, HTC Hero and other Android phones, they will find that by placing the phone horizontally or portraitically, the screen will change directions according to the position of the phone. This function needs to be achieved through gravity sensors. In addition to gravity sensors, there are many other types of sensors that are used in mobile phones, such as magnetoresistive sensors, which are the most important sensors. Although mobile phones can judge the direction through GPS, GPS is useless if the GPS signal is bad or there is no GPS signal at all. At this time, the direction (east, south, west, north) can be easily judged through the magnetoresistive sensor. With the magnetoresistive sensor, the electronicization of the compass (commonly known as the pointing needle) is also possible.
Using sensors in Android applications depends on interfaces. Through this interface, various events of the sensor can be monitored. The code of the SensorEventListener interface is as follows:
package ;
public interface SensorEventListener
{
public void
onSensorChanged(SensorEvent event);
public void
onAccuracyChanged(Sensor sensor, int accuracy);
}
There are two methods defined in the SensorEventListener interface: onSensorChanged and onAccuracyChanged. When the sensor value changes, for example, the onSensorChanged method is called when the direction of the magnetoresistive sensor changes. When the accuracy of the sensor changes, the onAccuracyChanged method is called.
The onSensorChanged method has only one parameter event of the SensorEvent type, where the SensorEvent class has a value variable, and the type of the variable is float[]. However, this variable has only 3 elements at most, and depending on the sensor, the meanings represented by the elements in the values variable are also different.
Before explaining the meaning of elements in the values variable, let’s first introduce how the coordinate system of Android defines the X, Y, and Z axes.
The direction of the X-axis is from left to right along the horizontal direction of the screen. If the phone is not square, shorter sides need to be placed horizontally and longer sides need to be placed vertically.
The Y-axis direction starts from the lower left corner of the screen and points to the top of the screen along the vertical direction of the screen.
Place your phone flat on the table, and the Z-axis direction is pointing to the sky from the phone.
Below is what the elements of the values variable represent in the main sensor.
1.1 Direction Sensor
In the direction sensor, the three values of the values variable represent degrees, and their meanings are as follows:
values[0]: This value indicates the orientation, which is the angle at which the phone rotates around the Z axis. 0 means North; 90 means East; 180 means South; 270 means West. If the value of values[0] is exactly these 4 values, and the phone is placed horizontally, it means that these 4 directions are in front of the phone. This feature can be used to implement the electronic compass, and Example 76 will introduce in detail the implementation process of the electronic compass.
values[1]: This value indicates the inclination, or the degree to which the phone is raised. This value changes when the phone tilts around the X-axis. The value range of values[1] is -180≤values[1]
≤180. Suppose you place your phone screen horizontally on the table, if the table is fully horizontal, the value of values[1] should be 0 (since few tables are absolutely horizontal, the value is likely not 0, but it is generally a certain value between -5 and 5). At this point, start lifting from the top of the phone until you rotate the phone 180 degrees along the X-axis (the screen is placed horizontally on the desktop). During this rotation, values[1] will vary between 0 and -180, that is, when lifted from the top of the phone, the value of values[1] will gradually decrease until it is equal to -180. If you start lifting from the bottom of the phone until you rotate the phone 180 degrees along the X-axis, values[1] will change between 0 and 180. That is, the value of values[1] will gradually increase until it is equal to 180. You can use values[1] and values[2] to be introduced below to measure the inclination of objects such as tables.
values[2]: represents the scrolling angle of the phone along the Y axis. The value range is -90≤values[2]≤90. Suppose you place the phone screen horizontally on the desktop, if the desktop is flat, the value of values[2] should be 0. When gradually lifting the left side of the phone, the value of values[2] gradually becomes smaller until the phone is placed perpendicular to the desktop. At this time, the value of values[2] is -90. When gradually lifting the right side of the phone, the value of values[2] gradually increases until the phone is placed perpendicular to the desktop. At this time, the value of values[2] is 90. Continue to scroll right or left when in vertical position, the value of values[2] continues to change between -90 and 90.
1.2 Acceleration Sensor
The three element values of the values variable of this sensor represent the acceleration values of the X, Y, and Z axes respectively. For example, if a phone placed horizontally on the desktop moves from the left to the right, values[0] are negative; if values[0] are positive, values[0] are positive. Readers can use the examples in this section to experience the changes in the value in the accelerated sensor. To use the corresponding sensor, it is not enough to implement the SensorEventListener interface only. You also need to use the following code to register the corresponding sensor.
// Get the sensor manager
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
// Register direction sensor
(this,
(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_FASTEST);
If you want to register another sensor, you can change the first parameter value of the getDefaultSensor method. For example, registering the acceleration sensor can use Sensor.TYPE_ACCELEROMETER. There are also many sensor constants defined in the Sensor class, but the sensor must be registered according to the actual hardware configuration in the mobile phone. If there is no corresponding sensor hardware in the phone, even if the corresponding sensor is registered, it will not work. The second parameter of the getDefaultSensor method indicates the speed at which the sensor data is obtained. SensorManager.SENSOR_DELAY_ FASTEST means to obtain sensor data as quickly as possible. In addition to this value, three speed values for obtaining sensor data can be set, these values are as follows:
SensorManager.SENSOR_DELAY_NORMAL: The default speed of obtaining sensor data.
SensorManager.SENSOR_DELAY_GAME: This value is recommended if you use sensors to develop games.
SensorManager.SENSOR_DELAY_UI: This value is recommended if you use a sensor to update data in the UI.
1.3 Gravity sensor
The type constant of the acceleration sensor is Sensor.TYPE_GRAVITY. The gravity sensor and the acceleration sensor use the same coordinate system. The three elements in the values array represent the gravity magnitude of the X, Y, and Z axes respectively. The Android SDK defines some constants that represent the gravity of planets, satellites, and the surface of the sun in galaxies. Let’s review the astronomical knowledge below. If you use Android phones outside the earth in the future, you may be able to use them.
public static final float GRAVITY_SUN= 275.0f;
public static final float GRAVITY_MERCURY= 3.70f;
public static final float GRAVITY_VENUS= 8.87f;
public static final float GRAVITY_EARTH= 9.80665f;
public static final float GRAVITY_MOON= 1.6f;
public static final float GRAVITY_MARS= 3.71f;
public static final float GRAVITY_JUPITER= 23.12f;
public static final float GRAVITY_SATURN= 8.96f;
public static final float GRAVITY_URANUS= 8.69f;
public static final float GRAVITY_NEPTUNE= 11.0f;
public static final float GRAVITY_PLUTO= 0.6f;
public static final float GRAVITY_DEATH_STAR_I= 0.000000353036145f;
public static final float GRAVITY_THE_ISLAND= 4.815162342f;
1.4 Light sensor
The type constant of the light sensor is Sensor.TYPE_LIGHT. The values array only has the first element (values[0]) meaningful. Indicates the intensity of light. The maximum value is 120000.0f. The Android SDK divides ray intensity into different levels. The maximum value of each level is represented by a constant. These constants are defined in the SensorManager class. The code is as follows:
public static final float LIGHT_SUNLIGHT_MAX =120000.0f;
public static final float LIGHT_SUNLIGHT=110000.0f;
public static final float LIGHT_SHADE=20000.0f;
public static final float LIGHT_OVERCAST= 10000.0f;
public static final float LIGHT_SUNRISE= 400.0f;
public static final float LIGHT_CLOUDY= 100.0f;
public static final float LIGHT_FULLMOON= 0.25f;
public static final float LIGHT_NO_MOON= 0.001f;
The above eight constants are just critical values. When readers actually use light sensors, they should determine a range according to actual conditions. For example, when the sun gradually rises, the value of values[0] is likely to exceed LIGHT_SUNRISE. When the value of values[0] gradually increases, it will gradually surpass LIGHT_OVERCAST and reach LIGHT_SHADE. Of course, if the weather is particularly good, it may also reach LIGHT_SUNLIGHT, or even higher.
1.5 gyroscope sensor
The type constant of the gyroscope sensor is Sensor.TYPE_GYROSCOPE. The meaning of the three elements of the values array is as follows: values[0]: the angular velocity of the rotation of the X-axis.
values[1]: The angular velocity of the rotation of the Y axis.
values[2]: The angular velocity of the rotation of the Z axis.
When the phone rotates counterclockwise, the angular velocity is positive, and when the phone rotates clockwise, the angular velocity is negative. Gyroscope sensors are often used to calculate the angle of the phone being rotated, and the code is as follows:
private static final float NS2S = 1.0f / 1000000000.0f;
private float timestamp;
public void onSensorChanged(SensorEvent event)
{
if (timestamp != 0)
{
// Represents the current time, in nanoseconds (1 millionth of a millisecond)
final float dT = ( - timestamp) * NS2S;
angle[0] += [0] * dT;
angle[1] += [1] * dT;
angle[2] += [2] * dT;
}
timestamp = ;
}
In the above code, the time difference (dT) of data obtained by the gyroscope sensor two adjacent times is calculated to calculate the angles of the rotation of the X, Y, and Z axes during this period, and the values are accumulated on different elements of the angle array respectively.
1.6 Other sensors
Other sensors introduce acceleration sensors, gravity sensors, light sensors, gyroscope sensors and direction sensors in the previous sections. In addition to these sensors, the Android SDK also supports several sensors as follows. Readers can refer to the official documentation for how to use these sensors and the constants and methods related to these sensors.
Proximity sensor (Sensor.TYPE_PROXIMITY)
Linear acceleration sensor (Sensor.TYPE_LINEAR_ACCELERATION)
Rotating vector sensor (Sensor.TYPE_ROTATION_VECTOR)
Magnetic field sensor (Sensor.TYPE_MAGNETIC_FIELD)
Pressure sensor (Sensor.TYPE_PRESSURE)
Temperature sensor (Sensor.TYPE_TEMPERATURE)
Although the AndroidSDK defines more than a dozen sensors, not every phone fully supports these sensors. For example, the Google Nexus S supports 9 of these sensors (not pressure and temperature sensors), while the HTC G7 only supports 5 of them. If you use a sensor that the phone does not support, an exception will generally not be thrown, but the data sent back by the sensor cannot be obtained. When using sensors, it is best for readers to determine whether the current phone supports the sensors they are using.