我正在测试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实现中缺少一些内容。
谢谢
答案 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文档以了解更多详细信息。