在Android 4.4以后的版本已经可以直接支持计步器sensor,参考下面的文章。
http://developer.android.com/about/versions/android-4.4.html#UserInput
http://motzcod.es/post/82515321689/part-1-my-stepcounter-android-step-sensors
http://baroqueworksdev.blogspot.com/2013/12/how-to-use-sensor-of-typestepdetector.html
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));
}
};