onSensorChanged未在模拟器中调用

时间:2017-07-21 06:03:50

标签: java android android-studio accelerometer sensormanager

我正在使用android工作室和Android 2.3模拟器。我无法找到为什么" onSensorChanged"当我改变加速度计的参数时不会调用。我通过stackoverflow搜索解决方案,但没有任何对我有用。

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor sensor;
    private TextView myTextView;

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

        myTextView = (TextView) findViewById(R.id.textView3);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this,
                sensor,
                SensorManager.SENSOR_DELAY_NORMAL);
        myTextView.setText("Waiting...");
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Sensor mySensor = event.sensor;

        if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            myTextView.setText((int) x);
        }
    }

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

    }

}

如您所见,我正在将textView3更改为值"等待..."并且在运行应用程序之后它仍然是等待......"。即使我改变了加速计传感器的参数,但它必须显示X值。

Emulator screenshot of the program

Sensors parameters

更新1

删除" sensorManager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_NORMAL);" in" onCreate"没有解决问题。我需要Android 2.3

更新2

似乎API 9不支持Accelerometer模拟器。 资料来源:https://stackoverflow.com/a/10612952/7878803

0 个答案:

没有答案