【问题标题】:Reading device's Proximity sensor with NativeScript使用 NativeScript 读取设备的接近传感器
【发布时间】:2019-08-09 02:28:11
【问题描述】:

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

有没有人为此在 Nativescript 中实现/编写了一个插件?

【问题讨论】:

  • 很遗憾目前还没有实现接近 api 的插件,你可能想写一个。
  • 谢谢。是的,我正在考虑为此目的编写一个插件。但我是 NativeScript 的新手,希望看到一个如何使用 NativeScript 获取 iOS 和 Android 的原生 API 的示例。谁能帮忙举个例子?
  • 我为此找到了部分解决方案 - 仅限 Android(如下)。当我完成 iOS 的代码时,我会为此编写一个插件。感谢您的帮助。

标签: nativescript nativescript-plugin


【解决方案1】:

我找到了我的问题的部分答案,即如何使用 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 解决方案(如果有)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多