The gravity sensor is similar to the direction sensor development step, as long as the value of x, Y and Z in the interim can be programmed according to their changes, it is recommended to learn about the Android app development tutorial .
First look at a picture
Assuming that the local gravitational acceleration value is g
When the phone is facing up, the z value is Q, and the z value is-g
When the right side of the phone face up, the value of X is G, the right side faces up, the value of X is-G
When the phone is facing up on the side, Y is the value of G, the right side facing up, Y is the value of-g
After understanding the meaning of x, Y and z in the gravity sensor, let's start learning how to use
First we create a sensor manager and a sensor listener that managers use to manage sensors and create a wide variety of sensors that monitor sensor changes and operate accordingly.
Private Sensormanager Sensormanager;
Private Mysensoreventlistener Mysensoreventlistener;
Mysensoreventlistener= new Mysensoreventlistener ();//This listener is, of course, defined by ourselves, and when the gravity sensor detects a change in the position of the mobile phone, we can take the appropriate action, here is the X, Y, The value of z is printed out
Private Final class Mysensoreventlistener implements sensoreventlistener{
@Override
Can get the change value of the sensor in real-time measurement
public void Onsensorchanged (Sensorevent event) {
Gravity sensor
if (Event.sensor.getType () ==sensor.type_accelerometer) {
float x = event.values[sensormanager.data_x];
Float y = event.values[sensormanager.data_y];
float z = event.values[sensormanager.data_z];
Tv_accelerometer is a TextView label on the interface, no longer repeat
Tv_orientation.settext ("Orientation:" +x+ "," +y+ "," +z ");
}
}
We create a gravity sensor in the Onresume method and register the listener with the system
protected void Onresume () {
Sensor sensor_accelerometer=sensormanager.getdefaultsensor (Sensor.type_accelerometer);
Sensormanager.registerlistener (Mysensoreventlistener,sensor_accelerometer, sensormanager.sensor_delay_ui);
Super.onresume ();
}
Finally we log off all sensors in OnPause () and release the Gravity sensor resources!
protected void OnPause () {
/logout of all sensor monitors
Sensormanager.unregisterlistener (Mysensoreventlistener);
Super.onpause ();
}
The above is the content of the gravity sensor, want to learn more about Android application development knowledge, please logine-Mentor Network。
The gravity sensor developed by Android