gpt4 book ai didi

java - 传感器更改不会触发 onSensorChanged

转载 作者:行者123 更新时间:2023-11-29 19:35:04 26 4
gpt4 key购买 nike

我昨天刚开始使用 android 和 java,但遇到了问题。我正在尝试将传感器的值输出到某些 TextView。文本更新,但使用定义时设置的值。 onSensorChanged 应该更新这些值吗?

import [...]

public class MainActivity extends Activity implements SensorEventListener {

public float[] gravity = {0,0,0};

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

final TextView gravxTxtView = (TextView) findViewById(R.id.gravxTxtView);
final TextView gravyTxtView = (TextView) findViewById(R.id.gravyTxtView);
final TextView gravzTxtview = (TextView) findViewById(R.id.gravzTxtView);

final Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
@Override
public void run() {
gravxTxtView.setText("Gravity x: " + Float.toString((gravity[0])));
gravyTxtView.setText("Gravity y: " + Float.toString((gravity[1])));
gravzTxtview.setText("Gravity z: " + Float.toString((gravity[2])));
}
}, 500);
}

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

@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
gravity[0] = event.values[0];
gravity[1] = event.values[1];
gravity[2] = event.values[2];
}
}
}

最佳答案

您缺少一些重要的步骤1.获取传感器管理器实例

SensorManager sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);

2。获取传感器实例

Sensor accel=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

3。将传感器注册到实现 SensorEventListener 的列表器类,在您的情况下,您已在 MainActivity 上实现,因此它将是 this

sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);

现在当某些变化发生时它会调用 onSensorChanged 方法,请告诉我它是否有效

关于java - 传感器更改不会触发 onSensorChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com