This class (mine is in Activity) inherits the SensorEventListener interface
First get the sensor object, then get the type of the sensor object
//Get sensor management object SensorManager mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); // Get the type of sensor (TYPE_ACCELEROMETER:acceleration sensor) Sensor mSensor = (Sensor.TYPE_ACCELEROMETER);
Here, in addition to obtaining acceleration sensors, we can also obtain other types of sensors, such as:
- * Sensor.TYPE_ORIENTATION: Direction sensor.
- * Sensor.TYPE_GYROSCOPE: Gyroscope sensor.
- * Sensor.TYPE_MAGNETIC_FIELD: Magnetic field sensor.
- * Sensor.TYPE_GRAVITY: Gravity sensor.
- * Sensor.TYPE_LINEAR_ACCELERATION: Linear acceleration sensor.
- * Sensor.TYPE_AMBIENT_TEMPERATURE: Temperature sensor.
- * Sensor.TYPE_LIGHT: Light sensor.
- * Sensor.TYPE_PRESSURE: Pressure sensor.
Rewrite the registration method
@Override protected void onResume(){ (); //Register listener for acceleration sensor (this, mSensor, SensorManager.SENSOR_DELAY_GAME); }
Rewrite the onSensorChanged method
@Override public void onSensorChanged(SensorEvent event){ values = ; StringBuilder sb = new StringBuilder(); ("Acceleration in the X direction:"); (values[0]); ("Acceleration in/nY direction:"); (values[1]); ("Acceleration in/nZ direction:"); (values[2]); (());//Open the output to the Imageview and you can see the change in acceleration }
Rewrite the method to cancel listening
@Override protected void onStop(){ (); //Cancel the monitoring (this); }
This will get acceleration.
Pass the values[] array to the object you need to use and you can use it.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the relevant links below