求支持Expo React Native的最新优质计步器库,expo-sensors暂不兼容Android
支持Expo React Native的计步器库推荐
1. expo-step-counter
- 这是Expo官方生态内专门针对计步功能的库,完美适配Android和iOS,无需 eject 项目。
- 核心特性:自动调用系统原生计步API,支持实时步数监听、历史步数查询,还能获取计步精度相关信息。
- 基础用法示例:
import * as StepCounter from 'expo-step-counter'; // 请求计步权限 const requestStepPermissions = async () => { const { status } = await StepCounter.requestPermissionsAsync(); if (status === 'granted') { // 监听实时步数变化 StepCounter.addStepCountListener((result) => { console.log('当前步数:', result.steps); }); } };
2. react-native-health(搭配Expo Config Plugin使用)
- 若你需要获取更全面的健康数据(不止计步),这个库适配Android的Google Fit和iOS的HealthKit,功能覆盖广。
- 注意事项:无需 eject 项目,但需通过Expo Config Plugin配置,在
app.json中添加对应配置后执行expo prebuild即可完成环境准备。 - 计步相关用法示例:
import HealthKit from 'react-native-health'; // 初始化并请求计步权限 const initHealthModule = async () => { const permissions = { read: ['stepCount'], write: [], }; const isAvailable = await HealthKit.isAvailable(); if (isAvailable) { await HealthKit.initHealthKit(permissions); // 查询今日步数 const todayStart = new Date(Date.now() - 86400000); const todayEnd = new Date(); const stepData = await HealthKit.getStepCount(todayStart, todayEnd); console.log('今日步数:', stepData); } };
3. @react-native-community/sensors(替代expo-sensors的社区方案)
- 作为
expo-sensors的替代社区库,它完善了Android端的传感器支持,你可以基于内置的加速度传感器自行实现计步逻辑。 - 优势:轻量无冗余,完全兼容Expo项目,无需额外配置。
- 基础计步逻辑示例:
import { Accelerometer } from '@react-native-community/sensors'; let stepCount = 0; let lastAccelValue = 0; // 设置传感器更新间隔 Accelerometer.setUpdateInterval(100); Accelerometer.subscribe(({ x, y, z }) => { const currentAccel = Math.sqrt(x*x + y*y + z*z); // 简易计步判断逻辑(可根据需求优化精度) if (currentAccel > 1.5 && lastAccelValue < 1.5) { stepCount++; console.log('累计步数:', stepCount); } lastAccelValue = currentAccel; });
补充提示
- 若你因
expo-sensors不支持Android计步而受阻,优先尝试expo-step-counter,它是官方生态中最适配的计步专用库,无需自行处理复杂的传感器逻辑。 - 使用涉及健康数据的库时,务必在
app.json(或对应平台配置文件)中添加权限说明,避免运行报错或审核不通过。
内容的提问来源于stack exchange,提问作者pavankommi
相关产品推荐
相关产品推荐

