计步器源代码实现的俩种方式

简介:

网上比较流行的计步好多都是用第一中方法写,是一套算法:

下边是第一种的代码,个人感觉准确度不是很好,误差经常在好几十往上,但是也还能用:下载地址:http://download.csdn.net/detail/u012808234/8539079

package com.example.pedometerdemo;

import java.util.List;
import java.util.Timer;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;



public class pedometerService extends Service implements SensorEventListener {

    public static final String STEP_CHANGE = "step_change";
    public static final String ADD_STEPS = "add_Step";
    
    private static final int notifiId = 11;
    private Intent intent;
    private ActivityManager activityManager;
    private SensorManager sensorManager;
    private Timer timer = new Timer();
    private long lastTime;// 上次记步的时间

    private float mLimit = 6.44f;
    private int interval_time;
    private float mLastValues[] = new float[3 * 2];
    private float mScale[] = new float[2];
    private float mYOffset;

    private float mLastDirections[] = new float[3 * 2];
    private float mLastExtremes[][] = { new float[3 * 2], new float[3 * 2] };
    private float mLastDiff[] = new float[3 * 2];
    private int mLastMatch = -1;

    private int startStep;

    private Service instance;
    
    private float[] xyz=new float[3];
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        instance = this;
        initData();
        initStepDetector();
        interval_time = 200;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        System.out.println("启动");
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        Sensor sensor = event.sensor;
        synchronized (this) {
            if (System.currentTimeMillis() - lastTime < interval_time) {
                return;
            }
            if (sensor.getType() == Sensor.TYPE_ORIENTATION) {
            } else {
                int j = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
                
                if (j == 1) {
                    float vSum = 0;
                    
                
                    for (int i = 0; i < 3; i++) {
                        final float v = mYOffset + event.values[i] * mScale[j];
                        
                        vSum += v;
                    }
                    int k = 0;
                    float v = vSum / 3;

                    float direction = (v > mLastValues[k] ? 1 : (v < mLastValues[k] ? -1 : 0));
                    if (direction == -mLastDirections[k]) {
                        // Direction changed
                        int extType = (direction > 0 ? 0 : 1); // minumum or
                                                                // maximum?
                        mLastExtremes[extType][k] = mLastValues[k];
                        float diff = Math.abs(mLastExtremes[extType][k] - mLastExtremes[1 - extType][k]);

                        if (diff > mLimit) {
                            boolean isAlmostAsLargeAsPrevious = diff > (mLastDiff[k] * 2 / 3);
                            boolean isPreviousLargeEnough = mLastDiff[k] > (diff / 3);
                            boolean isNotContra = (mLastMatch != 1 - extType);

                            if (isAlmostAsLargeAsPrevious && isPreviousLargeEnough && isNotContra) {
                                long currentTime = System.currentTimeMillis();
                                if (currentTime - lastTime > 2000) {
                                    
                                    startStep = 0;
                                } else {
                                   Log.e("STEP", startStep+++"");
                                }
                                mLastMatch = extType;
                                lastTime = currentTime;
                            } else {
                                mLastMatch = -1;
                            }
                        }
                        mLastDiff[k] = diff;
                    }
                    mLastDirections[k] = direction;
                    mLastValues[k] = v;
                }
            }
        }
    }

    private boolean appIsTop() {
        if (activityManager == null) {
            activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        }
        List<RunningTaskInfo> rti = activityManager.getRunningTasks(1);
        String packagename = rti.get(0).topActivity.getPackageName();
        if (packagename.equals(getPackageName())) {
            return true;
        }
        return false;
    }

    public void initStepDetector() {
        int h = 480; // TODO: remove this constant
        mYOffset = h * 0.5f;
        mScale[0] = -(h * 0.5f * (1.0f / (SensorManager.STANDARD_GRAVITY * 2)));
        mScale[1] = -(h * 0.5f * (1.0f / (SensorManager.MAGNETIC_FIELD_EARTH_MAX)));
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub

    }
    private void initData() {
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        if (sensorManager != null) {// 注册监听器
            sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
            // 第一个参数是Listener,第二个参数是所得传感器类型,第三个参数值获取传感器信息的频率
        }

    }
    
}


还有第二种,我觉得是误差小点的,自己测试了下,不管别的情况的,就是正常走路的误差在10步左右:看看代码,他是封成了好几个方法,上最主要的逻辑代码:

 下载地址:http://download.csdn.net/detail/u012808234/8539095

/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.android.apps.simplepedometer;

/**
 * Receives sensor updates and alerts a StepListener when a step has been detected.
 */
public class SimpleStepDetector {

  private static final int ACCEL_RING_SIZE = 50;
  private static final int VEL_RING_SIZE = 10;
  private static final float STEP_THRESHOLD = 4f;
  private static final int STEP_DELAY_NS = 250000000;

  private int accelRingCounter = 0;
  private float[] accelRingX = new float[ACCEL_RING_SIZE];
  private float[] accelRingY = new float[ACCEL_RING_SIZE];
  private float[] accelRingZ = new float[ACCEL_RING_SIZE];
  private int velRingCounter = 0;
  private float[] velRing = new float[VEL_RING_SIZE];
  private long lastStepTimeNs = 0;
  private float oldVelocityEstimate = 0;

  private StepListener listener;

  public void registerListener(StepListener listener) {
    this.listener = listener;
  }

  /**
   * Accepts updates from the accelerometer.
   */
  public void updateAccel(long timeNs, float x, float y, float z) {
    float[] currentAccel = new float[3];
    currentAccel[0] = x;
    currentAccel[1] = y;
    currentAccel[2] = z;

    // First step is to update our guess of where the global z vector is.
    accelRingCounter++;
    accelRingX[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[0];
    accelRingY[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[1];
    accelRingZ[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[2];

    float[] worldZ = new float[3];
    worldZ[0] = SensorFusionMath.sum(accelRingX) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
    worldZ[1] = SensorFusionMath.sum(accelRingY) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
    worldZ[2] = SensorFusionMath.sum(accelRingZ) / Math.min(accelRingCounter, ACCEL_RING_SIZE);

    float normalization_factor = SensorFusionMath.norm(worldZ);

    worldZ[0] = worldZ[0] / normalization_factor;
    worldZ[1] = worldZ[1] / normalization_factor;
    worldZ[2] = worldZ[2] / normalization_factor;

    // Next step is to figure out the component of the current acceleration
    // in the direction of world_z and subtract gravity's contribution
    float currentZ = SensorFusionMath.dot(worldZ, currentAccel) - normalization_factor;
    velRingCounter++;
    velRing[velRingCounter % VEL_RING_SIZE] = currentZ;

    float velocityEstimate = SensorFusionMath.sum(velRing);

    if (velocityEstimate > STEP_THRESHOLD && oldVelocityEstimate <= STEP_THRESHOLD
        && (timeNs - lastStepTimeNs > STEP_DELAY_NS)) {
      listener.step(timeNs);
      lastStepTimeNs = timeNs;
    }
    oldVelocityEstimate = velocityEstimate;
  }
}



相关文章
|
11月前
|
数据采集 API 调度
Python异步编程入门:告别“等待”的艺术
Python异步编程入门:告别“等待”的艺术
504 136
|
12月前
|
运维 Cloud Native 应用服务中间件
阿里云微服务引擎 MSE 及 API 网关 2025 年 11 月产品动态
阿里云微服务引擎 MSE 面向业界主流开源微服务项目, 提供注册配置中心和分布式协调(原生支持 Nacos/ZooKeeper/Eureka )、云原生网关(原生支持Higress/Nginx/Envoy,遵循Ingress标准)、微服务治理(原生支持 Spring Cloud/Dubbo/Sentinel,遵循 OpenSergo 服务治理规范)能力。API 网关 (API Gateway),提供 APl 托管服务,覆盖设计、开发、测试、发布、售卖、运维监测、安全管控、下线等 API 生命周期阶段。帮助您快速构建以 API 为核心的系统架构.满足新技术引入、系统集成、业务中台等诸多场景需要。
阿里云微服务引擎 MSE 及 API 网关 2025 年 11 月产品动态
|
8月前
|
SQL 人工智能 运维
Aloudata:从 A lot of data,到 AI on data
我们做的其实一直是同一件事: 先解决数据生产力的问题,让好数据更高效地被生产出来; 今天再进一步,让这些好数据不只是被人用,也能被 Agent 用。
|
人工智能 数据库 索引
超越幻觉:检索增强生成如何为AI大模型“装上”事实核查系统
超越幻觉:检索增强生成如何为AI大模型“装上”事实核查系统
724 107
|
10月前
|
人工智能 自然语言处理
效果评估:如何判断一个祝福 AI 是否“走心”
本文以「码上拜年」AI为例,探讨创意生成任务(如春节祝福)的评估困境:传统指标(loss、BLEU)失效,因“走心”无法量化。提出三维主观评估框架——事实准确、风格契合、表达自然,并强调评估核心是“人是否愿意直接发送”,即用户真实感受才是终极标准。
|
9月前
|
弹性计算 监控 安全
阿里云/本地部署OpenClaw图文教程+70个极简实用场景库分享:日常、内容、记忆、自动化、数据、安全全覆盖
本文基于2026年最新OpenClaw(Clawdbot)生态,整理70个极简可直接使用的真实场景,覆盖日常生活、内容转换、记忆管理、夜间自动化、数据分析、安全监控、工具开发七大类别。同时提供**阿里云ECS、MacOS、Linux、Windows11全平台部署流程**、**阿里云百炼Coding Plan免费大模型API完整配置**,以及高频问题一站式解答,所有命令可直接复制运行,无多余表述,适合所有用户快速上手。
574 0
|
11月前
|
人工智能 小程序 机器人
2026年阿里云无影云电脑一键部署 Moltbot(原 Clawdbot)指南 | 无影云电脑个人版
Moltbot(原Clawdbot)作为一款可理解自然语言并执行各类任务的AI助理,在日常办公与个人事务处理中实用性显著。对于追求便捷部署的用户而言,阿里云无影云电脑推出的专属部署方案,凭借预装镜像、简化配置等特性,规避了本地部署的诸多麻烦。以下为无影云电脑个人版一键部署Moltbot的详细流程,同时涵盖多消息通道配置及相关优化设置,助力不同需求的用户快速启用该AI助理。
1128 5
|
12月前
|
人工智能 自然语言处理 安全
2025年AI数字人公司新力量,集之互动0.8秒急速响应,构筑AI数字人核心壁垒
集之互动深耕AI数字人领域,以0.8秒极速响应、全栈私有化部署和高逼真3D技术为核心,打造安全可控、实时交互的数字员工。赋能医疗、文旅、零售等产业,助力企业降本增效,构建可持续的数字资产,推动AI商业落地。
602 4
|
11月前
|
自然语言处理
阿里云自然语言处理NLP免费试用,2026年最新免费申请百万调用额度
阿里云NLP免费试用,2026年最新百万调额度:基础版每日50万次、高级版累计50万次,自学习平台免费3个模型定制1个月,含文本翻译百万字符等10款产品,最长试用12个月。
|
敏捷开发 运维 数据可视化
提升协作效率的秘密武器:2025年DevOps任务可视化工具全解析
开发、测试、运维团队协作常因流程不透明导致效率低下,DevOps任务可视化工具成为解决这一痛点的关键方案。这类工具通过图形化呈现任务流程、状态追踪和CI/CD监控,实现跨团队协作透明化。核心功能包括看板管理、流水线可视化、自动告警等,能显著降低沟通成本,提升交付效率。市场主流工具如Jenkins、GitLab、板栗看板等各有优势,企业需根据规模、集成需求选择合适方案。随着AI和ChatOps发展,未来可视化工具将更智能化,助力企业构建高效DevOps闭环。
538 1