本文将实现一个名为Step_Counter(Boolean A)的函数,功能是统计从Step_Counter(Boolean.TRUE)到Step_Counter(Boolean.FALSE)这段时间里用户的步数。
首先查阅API文档,其中关于Step_Counter的描述如下:
TYPE_STEP_COUNTER
A constant describing a step counter sensor.
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. The timestamp of the event is set to the time when the first step for that event was taken. This sensor is implemented in hardware and is expected to be low power.
翻译过来的意思大概是:
用一个常量表示所走过的步数。
该传感器会返回从开机到目前为止的步数,返回值value的类型是float,但小数部分都是0,且该值只有在手机重启的时候才会归零。时间戳在触发这个事件的第一步(因为从开机自启动,所以时间戳的时间是开机后的第一步),这个传感器由硬件实现,且被耗电量很低。
附录源码:
private float StepCounter_Open=0; private float StepCounter_Close=0; private float StepCounter; private SensorEventListener StepCounterListener; public void StepCounter_Switch(Boolean A){ if (A==Boolean.TRUE){ StepCounter=0; Sensor mSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); StepCounterListener=new SensorEventListener() { @Override public void onSensorChanged(SensorEvent sensorEvent) { if (StepCounter_Open==0) { StepCounter_Open=sensorEvent.values[0]; } StepCounter_Close=sensorEvent.values[0]; } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }; mSensorManager.registerListener( StepCounterListener,mSensor,SensorManager.SENSOR_DELAY_GAME); } else{ mSensorManager.unregisterListener(StepCounterListener); StepCounter=StepCounter_Close-StepCounter_Open; StepCounter_Open=0; StepCounter_Close=0; mToast.makeText(mContext,Float.toString(StepCounter),Toast.LENGTH_SHORT).show(); } }测试成功,测试的时候走了八块一平米的方砖,一共用了九步,相对准确。