Implementation of Pedometer in Android

The principle of the pedometer is to simulate the pace and rhythm detection by swinging back and forth of the mobile phone. We have a pedometer sensor in the sensor of the mobile phone, so here we directly upload the code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_step"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="设备检测到您当前走了0步,总计数为0步"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

MainActivity.java

public class MainActivity extends BaseActivity
        implements SensorEventListener {

    private TextView tv_step;
    private SensorManager mSensorMgr;// 声明一个传感管理器对象
    private int mStep;
    private int mStepCount;

    @Override
    protected MvcBaseModel getModelImp() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initWidget() {
        tv_step = findViewById(R.id.tv_step);
        // 从系统服务中获取传感管理器对象
        mSensorMgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销当前活动的传感监听器
        mSensorMgr.unregisterListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册步行检测
        mSensorMgr.registerListener(this,
                mSensorMgr.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),
                SensorManager.SENSOR_DELAY_NORMAL);
        //注册步行计数
        mSensorMgr.registerListener(this,
                mSensorMgr.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR){//步行检测事件
            if (event.values[0] == 1.0f){
                mStep++;
            }
        }else if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER){//计步器事件
            mStepCount = (int) event.values[0];
        }
        String desc = String.format("设备检测到您当前走了%d步,总计数为%d步",mStep,mStepCount);
        tv_step.setText(desc);
    }

    //当传感器精度改变时回调该方法,一般无需处理
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
}

In this way, we have realized the function of a pedometer.

Guess you like

Origin blog.csdn.net/weixin_38322371/article/details/115323717