Search code examples
androidmultithreadingdelayaccelerometer

How to print accelerometer values every X seconds in Android


i want to print accelerometer values every 3 seconds. this is my code so far

@Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub

        if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER)
        {              
            x = a * x + (1 - a) * event.values[0];
            y = a * y + (1 - a) * event.values[1];
            z = a * z + (1 - a) * event.values[2];
              new Handler().postDelayed(new Runnable() {
                  @Override
                  public void run() {                     
                      printValue();
                  }
              }, 3000);                        
        }

    }

it's delaying output only when application launch ,what is my mistake and how to solve it?


Solution

  • You need to remove your Handler from onSensorChanged() so it will run constantly. Right now it will only execute if you have a change in your sensor reading. Also, you need to add a call to rerun the Runnable again, otherwise it will only execute once.

    //Outside of onSensorChanged(), perhaps in onCreate() of your Activity
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            printValue();
            new Handler().postDelayed(this, 3000);
        }
    }, 3000);