トラッキング コード

12/27/2013

How to use a Sensor of "TYPE_STEP_COUNTER"

Android API 19 add Sensor of "TYPE_STEP_COUNTER".

http://developer.android.com/reference/android/hardware/Sensor.html#TYPE_STEP_COUNTER


Initialize Sensor

We have to get a Sensor's Object from SensorManager.
Set the type "Sensor.TYPE_STEP_COUNTER".
public class StepCounterActivity extends Activity {
    private SensorManager mSensorManager;
    private Sensor mStepSensor;
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.text_step);

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mStepSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);

    }

    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(mSensorEventListener, mStepSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(mSensorEventListener);
    }


Create a SensorListener

We can get a step from onSensorChanged.
"event.values[0]" is a step counter.A sensor of this type returns the number of steps taken by the user since the last reboot while activated. The value is returned as a float (with the fractional part set to zero) and is reset to zero only on a system reboot.

    private SensorEventListener mSensorEventListener = new SensorEventListener() {
        private float mStepOffset;

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (mStepOffset == 0) {
                mStepOffset = event.values[0];
            }
            mTextView.setText(Float.toString(event.values[0] - mStepOffset));
        }
    };

6 comments:

  1. Hi,

    Have you check out accuracy in this sensor?

    Thanks

    ReplyDelete
    Replies
    1. I have a Nexus 5 Android 4.4.
      I tried to check accuracy of STEP_COUNTER .

      If you have a mobile phone in hand, this sensor reacts which is moving up and down even a little.
      If you put in a pants pocket mobile when you walk, This Sensor counts up correctly.
      This accuracy is not good enough.

      Thanks

      Delete
  2. Hi great explanation
    Do you know how to reset the value without rebooting the phone
    It will be great help
    Thanks

    ReplyDelete
    Replies
    1. Well, this is old. But did you get the answer? :D

      Delete
    2. As I understand, we can not do that, but we can save the previous value somewhere, then distract the value now with the previous value.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete