Realization of pedometer function by Android
- 2021-12-12 05:36:44
- OfStack
In this paper, we share the specific code of Android pedometer function for your reference. The specific contents are as follows
The principle of pedometer is to simulate pace rhythm detection by swinging back and forth of mobile phone. We have a pedometer sensor in the sensor of our mobile phone, so here we go directly to 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=" The device detects that you are currently gone 0 Steps, the total number is 0 Step "
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
MainActivity.java
public class MainActivity extends BaseActivity
implements SensorEventListener {
private TextView tv_step;
private SensorManager mSensorMgr;// Declaration 1 Sensor manager objects
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);
// Getting Sensor Manager Objects from System Services
mSensorMgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onPause() {
super.onPause();
// Log off the currently active sensor listener
mSensorMgr.unregisterListener(this);
}
@Override
protected void onResume() {
super.onResume();
// Registered walk detection
mSensorMgr.registerListener(this,
mSensorMgr.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),
SensorManager.SENSOR_DELAY_NORMAL);
// Register Walk Count
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){// Walk detection event
if (event.values[0] == 1.0f){
mStep++;
}
}else if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER){// Pedometer event
mStepCount = (int) event.values[0];
}
String desc = String.format(" The device detects that you are currently gone %d Steps, the total number is %d Step ",mStep,mStepCount);
tv_step.setText(desc);
}
// Callback the method when the sensor accuracy changes, 1 There is no need to deal with it
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
}
In this way, we realize the function of pedometer.