1

I am using an Accelerometer in my application and I am wondering if I can make it the way that accelerometer is only activates for a certain amount of time after the user has pressed a start button. It should stops when user press the stop button. It will essentially work as a pedometer which is part of a bigger application. This is the code used to implement the accelerometer:-

SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
    int sensorType = Sensor.TYPE_ACCELEROMETER;
    sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(sensorType),SensorManager.SENSOR_DELAY_NORMAL);

I have the code counting the steps which is:-

final SensorEventListener sensorListener = new SensorEventListener()
{

    public void onSensorChanged(SensorEvent event)
    {
            if(event.values[2]<3)
            {
                counter ++;
            }
            else if(event.values[2]>5)
            {
                counter --;
                counter ++;

            }
            sensorData.setText("Steps = "+ counter);

      }

      public void onAccuracyChanged(Sensor sensor, int accuracy){}
      };

I'm just wondering that since I'm counting the steps in the onSensorChanged method how do I limit this to only a button press state? Would it be possible to add a timer in to count how long has passed between the two button presses I mentioned earlier?

peter_budo
  • 1,748
  • 4
  • 26
  • 48
Darren Murtagh
  • 591
  • 2
  • 6
  • 28

1 Answers1

1

Yes, of course.

Prepare manager:

mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

Start accelerometer:

mSensorManager.registerListener(this, mAccelerometer, 
     SensorManager.SENSOR_DELAY_NORMAL);

Stop:

mSensorManager.unregisterListener(this);

Don't forget unregister listener in onPause() method.

Silver
  • 12,437
  • 2
  • 14
  • 11
  • ahh i see so the start accelerometer would go in the onclick for my start button and the stop would go in the stop. have any ideas what i could do with for a way of timing the session? – Darren Murtagh Apr 06 '12 at 23:26
  • You want miasure time between start and stop? Use System.currentTimeMillis(). – Silver Apr 07 '12 at 07:34