Accessability of native sensors in Nativescript

泪湿孤枕 提交于 2019-12-02 12:29:12

There will be no limitation to accessing any of the sensors. As you mentioned there is the accelerometer plugin and there are a few others. However, depending on the sensor you might have to write some of your logic to those APIs which shouldn't be too challenging if you're considering going with java/swift 😁. Here is something I've worked on recently where I needed the heart rate sensor on a WearOS app, this is not a production project at the moment, but it is planned to be released eventually.

As mentioned in the comments to the OP: You will end up using the Sensor Listener to access the data which is returned in the onSensorChanged event.

The following code is how to access the Heart Rate sensor on a device.

First, get the device Sensor Manager:

Import/require the application module from NS so you can access the Android activity in the sample below

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

  const activity: android.app.Activity =
    application.android.startActivity ||
    application.android.foregroundActivity;
  const mSensorManager = activity.getSystemService(
    android.content.Context.SENSOR_SERVICE
  ) as android.hardware.SensorManager;

Then create our listener:

const myHrListener = new android.hardware.SensorEventListener({
      onAccuracyChanged: (sensor, accuracy) => {},
      onSensorChanged: event => {
        console.log(event.values[0]);
        const HR = event.values[0].toString().split('.')[0];
        // HR is the BPM from the sensor here
      }
    });

Then we need to get the sensor:

const mHeartRateSensor = mSensorManager.getDefaultSensor(
    android.hardware.Sensor.TYPE_HEART_RATE
  );

Finally, we register the listener:

const didRegListener = mSensorManager.registerListener(
    myHrListener,
    mHeartRateSensor,
    android.hardware.SensorManager.SENSOR_DELAY_NORMAL
  );

The registerListener method returns a boolean so you can do a check if the boolean returned is true which means the listener was successful in registering and you'll get data when the sensor provides it in the onSensorChanged event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!