Reference version

This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo 传感器 iconExpo 传感器

一个提供访问设备加速度计、气压计、运动传感器、陀螺仪、光线传感器、磁力计和计步器的库。

Android
iOS
Web
Included in Expo Go
Recommended version:
~56.0.5

expo-sensors 提供了各种 API,用于访问设备传感器,以测量运动、方向、压力、磁场、环境光和步数。

安装

Terminal
npx expo install expo-sensors

If you are installing this in an existing React Native app, make sure to install expo in your project.

在 app 配置中进行配置

如果你的项目中使用了配置插件(Continuous Native Generation (CNG)),你可以使用 expo-sensors 内置的 配置插件 进行配置。该插件允许你配置一些无法在运行时设置的属性,这些属性需要构建新的应用二进制文件后才会生效。如果你的应用没有使用 CNG,那么你需要手动配置该库。

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-sensors", { "motionPermission": "允许 $(PRODUCT_NAME) 访问你的设备运动" } ] ] } }

Configurable properties

NameDefaultDescription
motionPermission"允许 $(PRODUCT_NAME) 访问你的设备运动"
Only for:
iOS

用于设置 NSMotionUsageDescription 权限消息的字符串,或使用 false 来禁用运动权限。

API

import * as Sensors from 'expo-sensors'; // 或者 import { Accelerometer, Barometer, DeviceMotion, Gyroscope, LightSensor, Magnetometer, MagnetometerUncalibrated, Pedometer, } from 'expo-sensors';

权限

Android

从 Android 12(API 级别 31)开始,系统对每个传感器更新都有 200Hz 的限制。

如果你需要大于 200Hz 的更新间隔,你必须将以下权限添加到你的 app.jsonexpo.android.permissions 数组里。

Android permissionDescription

HIGH_SAMPLING_RATE_SENSORS

Allows an app to access sensor data with a sampling rate greater than 200 Hz.

Are you using this library in an existing React Native app?

如果你没有使用 Continuous Native Generation(CNG),或者你是手动使用原生 android 项目,请将 HIGH_SAMPLING_RATE_SENSORS 权限添加到项目的 android/app/src/main/AndroidManifest.xml 中:

<uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />

iOS

此库使用以下用途说明键:

Info.plist keyDescription

NSMotionUsageDescription

A message that tells the user why the app is requesting access to the device’s motion data.

可用传感器

有关更多信息,请参阅你感兴趣的传感器文档:

Accelerometer

测量所有平台上的设备加速度。

Barometer

测量 Android 和 iOS 平台上的压力。

DeviceMotion

测量所有平台上的设备运动。

Gyroscope

测量所有平台上的设备旋转。

Magnetometer

测量 Android 和 iOS 平台上的磁场。

LightSensor

测量 Android 平台上的环境光。

Pedometer

测量 Android 和 iOS 平台上的步数。