本文介绍了onSensorChanged()不叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编码一个Android应用程序,但我必须使用加速度计一些麻烦。奇怪的是,我的功能onSensorChanged()不叫,我不知道为什么:/你能帮我吗? :)这里是我的code:
I am coding an Android application but I have some trouble using the accelerometer. Strangely, my function onSensorChanged() is not called and I don't know why :/ Could you help me please ? :) Here's my code :
@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);
}
}
在此先感谢:)
杰弗里
Thanks in advance :),Jeffrey
推荐答案
注册为传感器Sensor.TYPE_ACCELEROMETER而非Sensor.TYPE_ORIENTATION。
Register for the sensor Sensor.TYPE_ACCELEROMETER rather than Sensor.TYPE_ORIENTATION.
这篇关于onSensorChanged()不叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!