Android計步器的原理其實是通過手機的前后擺動模擬步伐節奏的監測。Android中與計步器有關的傳感器有兩個,一個是步行檢測(TYPE_STEP_DETECTOR),另一個是步行計數(TYPE_STEP_COUNTER)。其中,步行檢測的返回值為1時,表示當前檢測到一個步伐;步行計數的返回值是累加后的數值,表示本次開機激活后的總步伐數。
- layout/activity_main.xml界面布局代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextView
android:id="@+id/tv_step"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="走一走,看看有什么"android:textSize="20sp" /></LinearLayout>
package com.fukaimei.steptest;
import java.util.List;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {private TextView tv_step;
private SensorManager mSensroMgr;
private int mStepDetector =
0;
private int mStepCounter =
0;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv_step = (TextView) findViewById(R.id.tv_step);mSensroMgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE);}
@Overrideprotected void onPause() {
super.onPause();mSensroMgr.unregisterListener(
this);}
@Overrideprotected void onResume() {
super.onResume();
int suitable =
0;List<Sensor> sensorList = mSensroMgr.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensorList) {
if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {suitable +=
1;}
else if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {suitable +=
10;}}
if (suitable/
10>
0 && suitable%
10>
0) {mSensroMgr.registerListener(
this,mSensroMgr.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),SensorManager.SENSOR_DELAY_NORMAL);mSensroMgr.registerListener(
this,mSensroMgr.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),SensorManager.SENSOR_DELAY_NORMAL);}
else {tv_step.setText(
"當前設備不支持計步器,請檢查是否存在步行檢測傳感器和計步器傳感器");}}
@Overridepublic void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
if (event.values[
0] ==
1.0f) {mStepDetector++;}}
else if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {mStepCounter = (
int) event.values[
0];}String desc = String.format(
"設備檢測到您當前走了%d步,總計數為%d步",mStepDetector, mStepCounter);tv_step.setText(desc);}
@Overridepublic void onAccuracyChanged(Sensor sensor,
int accuracy) {}
}
總結
以上是生活随笔為你收集整理的Android移动开发-调用步行检测和步行计数传感器开发简易计步器的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。