Introduction to Android Sensor (onsensorchanged) _android

Source: Internet
Author: User
Tags constant current time documentation


The following are several constants defined in the API that represent sensor.






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 rotary instrument 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 was deprecated.SensorManager.getOrientation()use instead. magnetic field sensor
Int Type_pressure A constant describing a pressure sensor type pressure gauge sensor
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 these steps:



First step: Get Sensor Manager



Sensormanger sm = (Sensormanager). Getsystemservice (Sensor_service);



Step Two: Register the listener for the specific sensor, where we use the magnetoresistive sensor sensor.type_orientation.



Sm,registerlistener (This,sm.getdefaultsensor (sensor.type_orientation), sensormanager.sensor_delay_fastest);



If you want to register other sensors here, you can change the sensor type properties for the first parameter value. We should register according to the actual sensors in the phone. If the phone



We do not have the registered sensor, even if we register does not have any effect.



The third parameter value indicates the speed at which the sensor data is obtained, and Sensor_delay_fastest indicates that the sensor data is obtained as quickly as possible, in addition to the value, you can set 3 access



The speed value of the sensor data, these values are as follows:





Copy Code code as follows:

Sensor_delay_game This value is recommended if you are using a sensor to develop games. Most real-time rows are higher in the game using this level.
Sensor_delay_normal the default speed of obtaining sensor data. Standard delay, for the general puzzle game or easy to use the game can be used, but the low sampling rate may be on some racing games have a jump frame phenomenon.
SENSOR_DELAY_UI This value is recommended if you are using a sensor to update the UI.
Sensor_delay_fastest: Minimum latency, generally not particularly sensitive to processing is not recommended, this model may cause large consumption of mobile phone power, and due to the transmission of a large number of raw data, the algorithm can not handle the performance of the game logic and UI.





Step three, now that we've set up the monitor for the sensor in the second part. We are going to implement a specific listening method, in which applications use sensors that rely primarily on the Android.hardware.SensorEventListener interface. This interface can monitor various events on the sensor. The Sensoreventlistener interface code is as follows:





Copy Code code as follows:

Public interface Sensoreventlistener {
public void Onsensorchanged (Sensorevent event) {
}
public void onaccuracychanged (Sensor Sensor, int accuracy) {
}

}





Onsensorchanged () is invoked when the value of the sensor changes, such as when the reluctance sensor changes direction. The Onaccuracychanged () method is invoked when the sensor's precision changes.
First we can take a look at the comments and case codes in the Android development documentation:


public class Sensoractivity extends activity, implements Sensoreventlistener {
 private final Sensormanager Msensormanager;
 Private final Sensor Maccelerometer;

 Public sensoractivity () {
 Msensormanager = (sensormanager) getsystemservice (sensor_service);
 Maccelerometer = Msensormanager.getdefaultsensor (Sensor.type_accelerometer);
 }

 protected void Onresume () {
 super.onresume ();
 Msensormanager.registerlistener (This, maccelerometer, sensormanager.sensor_delay_normal);
 }

 protected void OnPause () {
 super.onpause ();
 Msensormanager.unregisterlistener (this);
 }

 public void onaccuracychanged (Sensor Sensor, int accuracy) {
 } public

 void Onsensorchanged (Sensorevent event) {
 }
 }


Always Make sure to disable sensors your don ' t need, especially when your the activity is paused. Failing to did can drain the battery in just a few hours. Note that the system won't disable sensors automatically when the screens turns off.



As you can see, the documents require that we do not need the sensor to be removed as much as possible, especially if our activity is in a state of loss of focus. If we do not follow the above, the cell phone battery will soon run out.



Also note that when the screen is closed, the sensor does not automatically unregister.



So we can use the OnPause () method and the Onresume () method in the activity. Registers a listener with the sensor in the Onresume method I, OnPause ()



method to remove the registration.



The following is a simple demo using the directional sensor


public class Sensoractivity extends activity, implements Sensoreventlistener {private final Sensormanager msensormanage
 R
 Private final Sensor Maccelerometer;
 Public sensoractivity () {Msensormanager = (Sensormanager) getsystemservice (Sensor_service);
 Maccelerometer = Msensormanager.getdefaultsensor (Sensor.type_accelerometer);
 } protected void Onresume () {super.onresume ();
 Msensormanager.registerlistener (This, maccelerometer, sensormanager.sensor_delay_normal);
 } protected void OnPause () {super.onpause ();
 Msensormanager.unregisterlistener (this); 
 

Onaccuracychanged (Sensor Sensor, int accuracy) {} public void Onsensorchanged (Sensorevent event) {}}
Package net.blogjava.mobile.sensor;
Import android.app.Activity;
Import Android.hardware.Sensor;
Import android.hardware.SensorEvent;
Import Android.hardware.SensorEventListener;
Import Android.hardware.SensorManager;
Import Android.os.Bundle;
Import Android.widget.TextView; public class OrientationsensoRtest extends activity implements Sensoreventlistener {private Sensormanager sensormanager = null;
 Private Sensor orientaionsensor = null;
 Private TextView TextView;
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.main);
 Settitle ("Directional sensor demo");
 TextView = (TextView) Findviewbyid (R.id.textview);
 Sensormanager = (Sensormanager) getsystemservice (Sensor_service);
 Orientaionsensor = Sensormanager. Getdefaultsensor (sensor.type_orientation);
 } @Override protected void OnPause () {super.onpause (); Sensormanager.unregisterlistener (this);
 Dismiss Listener Registration} @Override protected void Onresume () {super.onresume (); Sensormanager.registerlistener (This, orientaionsensor, sensormanager.sensor_delay_normal); Registering listener for sensor} @Override public void onaccuracychanged (Sensor Sensor, int accuracy) {} @Override public void Onsen
 Sorchanged (Sensorevent event) {float x = event.values[sensormanager.data_x]; FloaT y = event.values[sensormanager.data_y];
 float z = event.values[sensormanager.data_z];
 Textview.settext ("x=" + (int) x + "," + "y=" + (int) y + "," + "z=" + (int) z); }
}


Here's how android's coordinate system defines the x, y z axes.



The direction of the x-axis is the horizontal direction of the screen from left to right, if the cell phone is not a square, the shorter side needs to be placed horizontally, the longer side needs to be placed vertically.
The y-axis is directed from the bottom left corner of the screen to the top of the screen along the vertical direction of the screen.



Put the phone on the table, the direction of the z axis from the phone pointing to the sky.



Since Apple launched its first iphone in 2007, sensors that previously appeared to be out of hand with mobile phones have become an important part of the device's hardware. If readers use the iphone, HTC Dream, HTC Magic, HTC Hero, and other Android phones, they will find that by positioning the phone horizontally or vertically, the screen will change direction depending on the location of the phone. This function needs to be achieved by gravity sensors, in addition to gravity sensors, there are many other types of sensors are used in mobile phones, such as the reluctance sensor is the most important sensor. Although the mobile phone can be used to determine the direction of the GPS, but in the GPS signal is not good or no GPS signal, the GPS on the form of a fictitious. At this point through the reluctance sensor can easily determine the direction (east, south, west, north). With the reluctance sensor, it makes the compass (commonly known as pointing needle) electronic.
Using sensors in an Android application relies on the Android.hardware.SensorEventListener interface. This interface allows you to monitor the various events of the sensor. The code for the Sensoreventlistener interface is as follows:





Copy Code code as follows:

Package android.hardware;
public interface Sensoreventlistener
{
public void
Onsensorchanged (Sensorevent event);
public void
Onaccuracychanged (Sensor Sensor, int accuracy);
}





Two methods are defined in the Sensoreventlistener interface: Onsensorchanged and onaccuracychanged. The Onsensorchanged method is invoked when the sensor's value changes, for example, when the reluctance sensor's direction changes. The Onaccuracychanged method is invoked when the sensor's precision changes.
The Onsensorchanged method has only one sensorevent type argument event, where the Sensorevent class has a values variable that is very important, and the type of the variable is float[]. However, the variable has a maximum of 3 elements, and the elements in the values variable represent different meanings depending on the sensor.



Before explaining the meaning of elements in a values variable, let's first describe how the Android coordinate system defines x, Y, and Z axes.



The x-axis is oriented along the horizontal direction of the screen from left to right. If the cell phone is not a square, the shorter edges need to be placed horizontally, and the longer edges need to be placed vertically.
The y-axis is directed from the bottom left corner of the screen to the top of the screen along the vertical direction of the screen.
Put the phone flat on the table, the direction of the z axis from the phone to point to the sky.



The following are the meanings that the elements of the values variable represent in the primary sensor.



1.1 Direction Sensor



The 3 values of the value variables in the directional sensor represent degrees, and their meanings are as follows:



VALUES[0]: This value represents the orientation, which is the angle at which the phone rotates around the z axis. 0 represents northern (north), 90 for East (eastern), 180 for South (South), and 270 for West (western). If the value of values[0] is exactly these 4 values, and the cell phone is placed horizontally, it means that the phone is in front of the 4 directions. This feature can be used to achieve the electronic compass, example 76 will detail the implementation of the electronic compass process.



VALUES[1]: This value indicates the inclination, or the extent to which the phone is tilted. The value changes when the phone is tilted around the x axis. VALUES[1] The range of values is -180≤values[1]
≤180. If you put your phone screen up on the table, at this point, if the table is completely horizontal, the value of values[1] should be 0 (since very few tables are absolutely horizontal, the value is probably not 0, but typically a value between 5 and 5). Lift it from the top of the phone until you rotate the phone 180 degrees along the x axis (the screen is horizontally on the desktop). In this rotation, values[1] will change between 0 and 180, that is to say, when lifted from the top of the phone, the value of values[1 will gradually become smaller until it equals 180. If you start at the bottom of your phone until you rotate the phone 180 degrees along the x axis, values[1 will change between 0 and 180. The value of values[1] increases gradually until it equals 180. You can use Values[1] and the values[2 described below to measure the tilt of objects such as tables.



VALUES[2]: Indicates the mobile phone's scrolling angle along the y axis. The value range is -90≤values[2]≤90. Suppose you put your phone screen up on the desktop, and if the desktop is flat, the value of values[2] should be 0. When the left side of the phone is gradually raised, the value of values[2] gradually becomes smaller until the phone is placed perpendicular to the desktop, when the value of values[2] is 90. When the right side of the phone is gradually raised, the value of values[2] gradually increases until the phone is placed perpendicular to the desktop, when the value of values[2] is 90. Continue scrolling to the right or left at the vertical position, the value of values[2] continues to change between 90 and 90.



1.2 Speed sensor



The 3 element values of the value variables of the sensor represent the acceleration values of the X, Y, and z axes, respectively. For example, a phone that is placed horizontally on the desktop moves from the left to the right, values[0] to a negative value, and right-to-left moves, values[0] as positive. The reader can use the example in this section to realize the change in the value of the accelerator sensor. To use the appropriate sensor, it is not enough to implement the Sensoreventlistener interface, and you need to use the following code to register the appropriate sensor.





Copy Code code as follows:

Get sensor Manager
Sensormanager sm = (Sensormanager) getsystemservice (Sensor_service);
Register Direction Sensor
Sm.registerlistener (This,
Sm.getdefaultsensor (sensor.type_orientation),
Sensormanager.sensor_delay_fastest);





If you want to register another sensor, you can change the value of the 1th parameter of the Getdefaultsensor method, for example, the registration accelerator can use Sensor.type_accelerometer. Many sensor constants are also defined in the Sensor class, but the sensor is registered according to the actual hardware configuration on the phone. If the phone does not have the appropriate sensor hardware, even if the corresponding sensor registration does not play any role. The 2nd parameter of the Getdefaultsensor method represents the speed at which sensor data is obtained. Sensormanager.sensor_delay_ fastest means to get sensor data as quickly as possible. In addition to this value, you can set 3 speed values for sensor data, which are as follows:



Sensormanager.sensor_delay_normal: The default speed of obtaining sensor data.
Sensormanager.sensor_delay_game: This value is recommended if you are using a sensor to develop a game.
SENSORMANAGER.SENSOR_DELAY_UI: This value is recommended when using sensors to update data in the UI.



1.3 Gravity Sensor



The type constants of the accelerometer are sensor.type_gravity. The gravitational sensor uses the same set of coordinates as the accelerometer. The three elements in the values array represent the gravity size of the X, Y, and z axes, respectively. The Android SDK defines constants that represent the gravity of planets, moons, and the surface of the sun in galaxies. Here is a review of astronomy knowledge, in the future if you use Android phones outside the Earth, may be used.





Copy Code code as follows:

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 Ray Sensor





The type constants of the light sensor are sensor.type_light. Values array only the first element (Values[0]) is meaningful. Indicates the intensity of the light. The maximum value is 120000.0f. The Android SDK divides the intensity of light into different levels, and the maximum value of each level is represented by a constant, which is defined in the Sensormanager class with the following code:





Copy Code code 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 eight constants above are only critical values. In practical use of light sensor, the reader should determine a range according to the actual situation. For example, when the sun gradually rises, the value of values[0] is likely to exceed the light_sunrise, when the value of values[0] gradually increases, it will gradually over the light_overcast, and achieve light_shade, of course, if the day is particularly good, may also reach light_sunlight, or even higher.

1.5 Gyroscope Sensors
The type constants of the gyroscope sensors are sensor.type_gyroscope. The three elements of the values array represent the following meanings: Values[0]: The angular velocity of the rotation of the x axis.
VALUES[1]: The angular speed of the rotation of the Y axis.
VALUES[2]: The angular speed at which the z axis rotates.
When the phone rotates counterclockwise, the angular velocity is positive and the angular velocity is negative when rotated clockwise. Gyroscope sensors are often used to calculate the angle of the mobile phone's rotation, the code is as follows:





Copy Code code as follows:

Private static final float ns2s = 1.0f/1000000000.0f;
private float timestamp;
public void Onsensorchanged (Sensorevent event)
{
if (timestamp!= 0)
{
Event.timesamp represents the current time, in nanoseconds (1 One out of 10,000 milliseconds)
Final float DT = (event.timestamp-timestamp) * NS2S;
Angle[0] + = event.values[0] * DT;
ANGLE[1] + = event.values[1] * DT;
ANGLE[2] + = event.values[2] * DT;
}
timestamp = Event.timestamp;
}





In the code above, the gyro sensor obtains data from neighboring two times (DT) to calculate the angle of the mobile phone's rotation x, Y, Z axis in this time, and add the values to the different elements of the angle array respectively.

1.6 Other Sensors
Other sensors in the previous sections introduced acceleration sensors, gravity sensors, light sensors, gyroscope sensors and directional sensors. In addition to these sensors, the Android SDK also supports several of the following sensors. Readers can refer to the official documentation for the use of these sensors and the constants and methods associated with these sensors.



Proximity sensor (sensor.type_proximity)
Linear acceleration Sensor (sensor.type_linear_acceleration)
Rotational vector sensor (sensor.type_rotation_vector)
magnetic field sensor (Sensor.type_magnetic_field)
Pressure transducer (sensor.type_pressure)
Temperature sensor (Sensor.type_temperature)



Although ANDROIDSDK defines more than 10 kinds of sensors, not every cell phone fully supports these sensors. For example, Google Nexus s supports 9 of these sensors (no pressure and temperature sensors are supported), while HTC G7 only supports 5 of these sensors. If you use a sensor that is not supported by your mobile phone, you typically do not throw an exception, but you cannot get the data returned by the sensor. It is best for readers to determine whether the current phone supports the sensor used when using the sensor.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.