我正在尝试将以下代码改为使用罗盘,但我遇到了麻烦。我尝试使用SensorEventListener,但我失败了。是否有任何教程可供我参考?任何帮助都将不胜感激。
private static SensorListener orientationListener;
private static boolean isTrackingOrientation = false;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
orientationListener = new SensorListener() {
public void onSensorChanged(int s, float v[]) {
float northDirection = v[android.hardware.SensorManager.DATA_X];
((QiblaCompassView)findViewById(R.id.qibla_compass)).setDirections(northDirection, VARIABLE.qiblaDirection);
}
public void onAccuracyChanged(int s, int a) {
}
};
}
@Override
public void onResume() {
startTrackingOrientation();
super.onResume();
}
@Override
public void onPause() {
stopTrackingOrientation();
super.onPause();
}
private void startTrackingOrientation() {
if(!isTrackingOrientation) isTrackingOrientation = ((SensorManager)getSystemService(SENSOR_SERVICE)).registerListener(orientationListener, android.hardware.SensorManager.SENSOR_ORIENTATION);
}
private void stopTrackingOrientation() {
if(isTrackingOrientation) ((SensorManager)getSystemService(SENSOR_SERVICE)).unregisterListener(orientationListener);
isTrackingOrientation = false;
}