SensorEventListener似乎没有运行。如何获取传感器值?

时间:2018-09-18 13:19:49

标签: android wear-os android-sensors

我正在测试android磨损传感器以用于将来的实现。我的目标是获取心率值,并将其显示在MainActivity中。所以我实现了SensorHelper class

import static android.content.Context.SENSOR_SERVICE;

public class SensorHelper implements SensorEventListener {

    private final SensorManager mSensorManager;
    private final Sensor mHeartRate;
    public String sensorValue = "deafult";

    public SensorHelper() {
        Log.i("SENSOR", "SENSOR CONSTRUCTOR");
        mSensorManager = (SensorManager) MyApplication.getAppContext().getSystemService(SENSOR_SERVICE);
        mHeartRate = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
            String msg = "" + (int)event.values[0];
            this.sensorValue = msg;
            Log.d("SENSOR", msg);
        }
        else
            this.sensorValue = "unable to read value";
            Log.d("SENSOR", "Unknown sensor type");
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
}

据我所知,每次心率变化时,都应调用onSensorChanged函数。在此功能中,我正在更新sensorValue变量。

MainActivity.class中,我创建了一个按钮,通过为其分配TextView的值来刷新Sensorhelper.sensorValue

public class MainActivity extends WearableActivity {

    private Button refreshButton;
    private TextView mTextView;
    SensorHelper sensorHelper;

    private View.OnClickListener refreshListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("refresh");
            mTextView.setText(sensorHelper.sensorValue);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sensorHelper = new SensorHelper();

        mTextView = (TextView) findViewById(R.id.textView);
        refreshButton = (Button) findViewById(R.id.button_refresh);
        refreshButton.setOnClickListener(refreshListener);

        // Enables Always-on
        setAmbientEnabled();
    }
} 

我添加了BODY_SENSORS权限。问题是TextView始终保持“默认”状态,并且按钮不刷新值。我认为我在SensorHelper实现中缺少一些内容。

谢谢

1 个答案:

答案 0 :(得分:0)

您错过了为获取新值而注册侦听器的呼叫。

在您的SensorHelper构造函数中,添加mSensorManager.registerListener(this, mHeartRate, SensorManager.SENSOR_DELAY_NORMAL);

public SensorHelper() {
    Log.i("SENSOR", "SENSOR CONSTRUCTOR");
    mSensorManager = (SensorManager) MyApplication.getAppContext().getSystemService(SENSOR_SERVICE);
    mHeartRate = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
    mSensorManager.registerListener(this, mHeartRate, SensorManager.SENSOR_DELAY_NORMAL);
}

当您不再需要传感器时,请记住拨打电话mSensorManager.unregisterListener(this);

查看SensorManager文档以了解更多详细信息。