nativescript-android-sensors
NativeScript 插件,用于使用 Android 设备传感器。传感器在后台线程中运行。
npm i --save nativescript-android-sensors

NativeScript-Android-Sensors

NativeScript 插件,用于使用在后台线程运行的 Android 设备传感器。

npm

安装

NativeScript 7+

ns plugin add nativescript-android-sensors

低于 7 的 NativeScript 版本

tns plugin add [email protected]

Android 传感器:https://android-docs.cn/reference/android/hardware/Sensor.html

使用

import { AndroidSensors, AndroidSensorListener, SensorDelay } from 'nativescript-android-sensors';

const sensors = new AndroidSensors();
const accelerometerSensor: android.hardware.Sensor;
const gyroScope: android.hardware.Sensor;

const sensorListener = new AndroidSensorListener({
onAccuracyChanged: (
sensor: android.hardware.Sensor,
accuracy: number
) => {
console.log('accuracy', accuracy);
},
onSensorChanged: (result: string) => {
// result is being returned as a string currently
const parsedData = JSON.parse(result);
const rawSensorData = parsedData.data;
const sensor = parsedData.sensor;
const time = parsedData.time;
}
});

this.sensors.setListener(sensorListener);


someFunction() {
accelerometerSensor = sensors.startSensor(android.hardware.Sensor.TYPE_LINEAR_ACCELERATION, SensorDelay.FASTEST);

// here we are using the android const 4 which is for the TYPE_GYROSCOPE sensor
// https://android-docs.cn/reference/android/hardware/Sensor.html#TYPE_GYROSCOPE
// we are passing the third argument to `startSensor` which is for maxReportLatency, if the sensor is able to support FIFO this will register the sensor with the reporting latency value, if not, the sensor registers on the background thread as normal
const gyroScope = sensors.startSensor(4, SensorDelay.NORMAL, 4000000);

// maybe you wanna use a timeout and stop it after 8 seconds
setTimeout(() => {
sensors.stopSensor(gyroScope);
}, 8000)
}

functionToStopTheSensorData() {
sensors.stopSensor(accelerometerSensor);
}

API

构造函数

AndroidSensors (liteData: boolean = false)

liteData 的布尔参数改变了传感器事件更改返回的 JSON。这在您通过减少传感器更改事件中的冗余数据来存储大量数据集时很有用。

import {
AndroidSensors,
AndroidSensorListener,
SensorDelay,
} from 'nativescript-android-sensors';

const sensors = new AndroidSensors(true);

方法

  • setListener(listener: AndroidSensorListener): void
    • 设置当传感器更改时返回数据的监听器。
  • startSensor(sensor: android.hardware.Sensor, delay: SensorDelay, maxReportingDelay?: number): android.hardware.Sensor
    • 使用提供的报告延迟注册传感器。返回传感器的实例,以便将其传递给 stopSensor(sensor) 方法以注销。startSensor 的第三个参数用于最大报告延迟,如果传感器支持 FIFO,则将传感器注册为具有报告延迟值的传感器,如果不支持,则传感器将在后台线程上正常注册
  • stopSensor(sensor: android.hardware.Sensor): void
    • 注销传感器。
  • getDeviceSensors(): android.hardware.Sensor[]
    • 返回设备传感器的数组。
  • flush(): boolean
    • 将从监听器中清除事件数据。如果成功清除,则返回 true。