onSensorChanged()未调用

时间:2014-08-02 12:31:26

标签: android accelerometer sensor

我正在编写Android应用程序,但我在使用加速度计时遇到了一些麻烦。奇怪的是,我的函数onSensorChanged()没有被调用,我不知道为什么:/你能帮帮我吗? :)这是我的代码:

@SuppressLint("NewApi") 
public class Game extends Activity implements SensorEventListener {

SensorManager sensorManager;
ImageView vaisseau;
TextView test;
RelativeLayout rl;

@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_GAME);

    setContentView(R.layout.game);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    Display ecran = getWindowManager().getDefaultDisplay(); 
    int largeur= ecran.getWidth();
    int hauteur= ecran.getHeight();

    Drawable d = getResources().getDrawable(R.drawable.spaceship);
    int largeurVaisseau = d.getIntrinsicWidth();

    vaisseau = new ImageView(this);
    vaisseau.setImageResource(R.drawable.spaceship);
    rl = (RelativeLayout)findViewById(R.id.layout_game);
    vaisseau.setX(largeur/2 - largeurVaisseau);
    vaisseau.setY(hauteur-hauteur*10/100);
    rl.addView(vaisseau);

    test = new TextView(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return true;
}

public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
        test.setText(Float.toString(event.values[0]));
        rl.addView(test);
    }
}   

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

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

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

提前谢谢:), 杰弗里

1 个答案:

答案 0 :(得分:1)

注册传感器Sensor.TYPE_ACCELEROMETER而不是Sensor.TYPE_ORIENTATION。