我正在编写一个指南针应用程序,但由于某些原因无法访问所需的传感器。我已经实现了SensorEventListener
接口,并通过以下方式注册我的传感器:
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
在我的
onSensorChange()
方法中:public void onSensorChanged(SensorEvent event) {
Toast t = Toast.makeText(this, "onSensorChanged", Toast.LENGTH_LONG);
t.setGravity(Gravity.TOP, 0, 0);
t.show();
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
mGravity = event.values;
}
if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
mGeomagnetic = event.values;
}
if(mGravity !=null && mGeomagnetic !=null){
float [] R = new float[9];
float [] I = new float [9];
boolean success = sensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if(success){
float [] orientation = new float [3];
sensorManager.getOrientation(R, orientation);
north = orientation[0];
}
}
}
Toast
消息不会在屏幕上显示,当我尝试将 north 值放入 TextView
中时,输出结果为 0
。如果有人能给我解释一下为什么我无法访问 onSensorChanged()
方法就太好了。清单文件中的权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>