我找到了我的问题的部分答案,即如何使用 NativeScript 在 Android 中读取接近传感器。一旦我为 iOS 编写代码,我也会更新我的答案。
要访问 Android 中的传感器,首先我们必须导入 NS 提供的“应用程序”和“平台”模块:
import * as application from "tns-core-modules/application";
import * as platform from 'tns-core-modules/platform';
declare var android: any;
然后,获取android的Sensor Manager,接近传感器并创建一个android事件监听器并注册它来监听接近传感器的变化。
注册接近传感器:
registerProximityListener() {
// Get android context and Sensor Manager object
const activity: android.app.Activity = application.android.startActivity || application.android.foregroundActivity;
this.SensorManager = activity.getSystemService(android.content.Context.SENSOR_SERVICE) as android.hardware.SensorManager;
// Creating the listener and setting up what happens on change
this.proximitySensorListener = new android.hardware.SensorEventListener({
onAccuracyChanged: (sensor, accuracy) => {
console.log('Sensor ' + sensor + ' accuracy has changed to ' + accuracy);
},
onSensorChanged: (event) => {
console.log('Sensor value changed to: ' + event.values[0]);
}
});
// Get the proximity sensor
this.proximitySensor = this.SensorManager.getDefaultSensor(
android.hardware.Sensor.TYPE_PROXIMITY
);
// Register the listener to the sensor
const success = this.SensorManager.registerListener(
this.proximitySensorListener,
this.proximitySensor,
android.hardware.SensorManager. SENSOR_DELAY_NORMAL
);
console.log('Registering listener succeeded: ' + success);
}
要取消注册事件侦听器,请使用:
unRegisterProximityListener() {
console.log('Prox listener: ' + this.proximitySensorListener);
let res = this.SensorManager.unregisterListener( this.proximitySensorListener);
this.proximitySensorListener = undefined;
console.log('unRegistering listener: ' + res);
};
当然,我们可以将 android.hardware.Sensor.TYPE_PROXIMITY 更改为 Android OS 提供给我们的任何其他传感器。在Android Sensor Overview 中了解有关传感器的更多信息。我没有用其他传感器检查这个,所以实现可能有点不同,但我相信这个概念还是一样的
此解决方案基于 Brad Martin 的解决方案 here。
为使此答案完整,请发布您的 iOS 解决方案(如果有)。