トラッキング コード

12/28/2013

How to use a Sensor of "TYPE_STEP_DETECTOR"

A sensor of this type triggers an event each time a step is taken by the user.

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


Initialize Sensor

We have to get a Sensor's Object from SensorManager.
Set the type "Sensor.TYPE_STEP_DETECTOR".
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_DETECTOR);

    }

    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 trigger from onSensorChanged.

    private SensorEventListener mSensorEventListener = new SensorEventListener() {
        private int mStep;

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

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.values[0] == 1.0f) {
                mStep++;
            }
            mTextView.setText(Integer.toString(mStep));
        }
    };

No comments:

Post a Comment