传感器更改不会触发onSensorChanged

时间:2016-09-04 09:29:15

标签: java android android-studio android-sensors

我昨天刚刚开始使用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 个答案:

答案 0 :(得分:2)

你缺少一些严肃的步骤 1.获取传感器管理器的实例

SensorManager sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);

2。获取传感器的实例

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

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

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

现在当发生某些变化时会调用onSensorChanged方法,请告诉我其工作与否