我正在尝试更改以下代码以使用指南针,但是,我遇到了麻烦,我尝试使用 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;
}