我正在尝试使用 android 中的传感器构建一个简单的计步器,我很确定响应很简单,但实际上我无法弄清楚
public class Main2Activity extends AppCompatActivity {
private SensorManager sensorManager;
private Sensor pedometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
pedometer = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorListener, pedometer);
}
private final SensorEventListener sensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// Mettre à jour uniquement dans le cas de notre capteur
if (event.sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
TextView txtpas = findViewById(R.id.Podometre);
txtpas.setText(String.valueOf(event.values[0]));
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorListener, pedometer, SensorManager.SENSOR_DELAY_NORMAL);
}
}
看起来很简单,但它实际上从不去 sensorListener,有人知道吗?感谢