1.新手每天都碰到很多新问题,今天看书,随着书本写了一个方向传感器的小例子,就是想验证一下是否这么用方向传感器,可是写出来以后,Log出来的值都是0,和书本不一样呀,又上网查了一下,貌似没有写错,可就是结果不对呀
2.贴上全部代码,求大家指点呀
public class MainActivity extends AppCompatActivity {
private SensorManager sensorManager;
private SensorEventListener listener=new SensorEventListener() {
float[] magValues=new float[3];
float[] accValues=new float[3];
float[] r=new float[9];
float[] values=new float[3];
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
accValues=event.values.clone();
Log.d("MainActivity","accelerometer");//结果不对,为了调试加入的
}
else if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
magValues=event.values.clone();
Log.d("MainActivity","magnetic");//结果不对,为了调试加入的
}
SensorManager.getRotationMatrix(r,null,accValues,magValues);
SensorManager.getOrientation(r,values);
Log.d("MainActivity","values[0]="+Math.toDegrees(values[0]));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor magneticSensor=sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
Sensor accSensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listener,magneticSensor,SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(listener,accSensor,SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onDestroy() {
super.onPause();
if(sensorManager!=null){
sensorManager.unregisterListener(listener);
}
}
}
运行结果永远是
D/MainActivity: accelerometer
D/MainActivity: values[0]=0
就是说magnetic永远触发不了
3.测试的是真机,华为手机,系统是安卓5.0的
要疯了,求指点
PHP中文网2017-04-17 17:56:06
Today I used the simulator that comes with Android Studio to run it. I can simulate the shaking and movement of the phone and get numerical values. This means that the above program should have no problem with the native system. Is there any special regulations for Huawei phones?