使用 NativeScript 读取设备的接近传感器

Reading device's Proximity sensor with NativeScript

我正在开发一个跨平台的移动应用程序,我需要读取设备的接近传感器,它使用设备的接近传感器提供有关附近物理对象距离的信息。

有人在 Nativescript 中实现了 this/wrote 用于此目的的插件吗?

我找到了关于如何使用 NativeScript 在 Android 中读取接近传感器的问题的部分答案。我也会在为 iOS 编写代码后更新我的答案。

要访问 Android 中的传感器,首先我们必须导入 NS 提供的 'application' 和 'platform' 模块:

import * as application from "tns-core-modules/application";
import * as platform from 'tns-core-modules/platform';

declare var android: any;

然后,获取android的传感器管理器,接近传感器并创建一个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 的解决方案

为了使这个答案完整,请 post 如果你有 iOS 的解决方案。