Android Sensor Acceleration Sensor of SensorEventListener

  • 2021-11-02 02:12:34
  • OfStack

This class (mine is in Activity) inherits the SensorEventListener interface

Get the sensor object first, and then get the type of the sensor object


// Getting the Sensor Management Object 
    SensorManager mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
     //  Get the type of sensor (TYPE_ACCELEROMETER: Acceleration sensor )
    Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

Here we can obtain other types of sensors besides acceleration 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: Optical sensor. * Sensor.TYPE_PRESSURE: Pressure sensor.

Override the registration method


@Override
  protected void onResume(){
    super.onResume();
    // Register the listener for the acceleration sensor 
    mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_GAME);
  }

Override the onSensorChanged method


@Override
   public void onSensorChanged(SensorEvent event){
     values = event.values;
     StringBuilder sb = new StringBuilder();
     sb.append("X Acceleration in direction: ");
     sb.append(values[0]);
     sb.append("/nY Acceleration in direction: ");
     sb.append(values[1]);
     sb.append("/nZ Acceleration in direction: ");
     sb.append(values[2]);
     mTextValue.setText(sb.toString());// Output to Imageview On, you can see the change of acceleration 
   }

Override the method of unlistening


  @Override
  protected void onStop(){
    super.onStop();
    // Cancel listening 
    mSensorManager.unregisterListener(this);
  }

In this way, we can get acceleration.

You can use the values [] array by passing it to the object you need to use.

Summarize


Related articles: