The development steps of the gravity sensor and the direction sensor are similar. After clarifying the values of X, Y, and Z in the period, you can program based on their changes. First, let's look at a figure.
Assume that the local acceleration value is G.
When the mobile phone is facing up, the value of Z is Q, and the value of Z is-G.
When the right side of the mobile phone is up, the value of X is g, and the value of X is-G. When the right side is up, the value of Y is G, when the right side is facing up, the value of Y is-G. After learning the meanings of X, Y, and Z in the gravity sensor, let's start to learn how to use them.First, we create a sensor manager and a sensor listener. The manager is used to manage the sensor and create various sensors. The Listener is used to monitor sensor changes and perform relevant operations. Private sensormanager; private mysensoreventlistener; mysensoreventlistener = new mysensoreventlistener (); // Of course, this listener is defined by ourselves. When the operator senses a change in the location of the mobile phone, we can take the corresponding action. Here, the values of X, Y, and Z are printed tightly.Private final class mysensoreventlistener implements Sensoreventlistener {@ Override // obtain the variable value measured by the sensor in real time. Public void onsensorchanged (sensorevent event) {// 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. Do not repeat TV _orientation.settext ("orientation:" + x + "," + Y + "," + Z );}} we create a gravity sensor in the onresume method and register the listener protected void onresume (){ Sensor sensor_accelerometer = sensormanager. getdefasensensor (sensor. type_accelerometer ); Sensormanager. registerlistener (mysensoreventlistener, sensor_accelerometer, Sensormanager. sensor_delay_ui );Super. onresume ();} Finally, We deregistered all sensor monitors in onpause () to release gravity sensor resources! Protected void onpause () {/cancel all sensor listening sensormanager. unregisterlistener (mysensoreventlistener); Super. onpause ();} Here, the introduction of gravity sensor is complete!
Reprinted: http://blog.sina.com.cn/s/blog_5a48dd2d0100u5ej.html