リンクを使用したheromの回答から:http://android-coding.blogspot.co.at/2012/03/create-our-android-compass.html
クラスを拡張してセンサーを実装しました。extends Activity implements SensorEventListener
提案どおりに実装しましたが、画面の向きを考慮して修正しました。
これが私が行ったコードです:
@Override
public void onSensorChanged(SensorEvent event) {
switch(event.sensor.getType()){
case Sensor.TYPE_ACCELEROMETER:
for(int i =0; i < 3; i++){
valuesAccelerometer[i] = event.values[i];
}
break;
case Sensor.TYPE_MAGNETIC_FIELD:
for(int i =0; i < 3; i++){
valuesMagneticField[i] = event.values[i];
}
break;
}
boolean success = SensorManager.getRotationMatrix(
matrixR,
matrixI,
valuesAccelerometer,
valuesMagneticField);
if(success){
SensorManager.getOrientation(matrixR, matrixValues);
double azimuth = Math.toDegrees(matrixValues[0]);
//double pitch = Math.toDegrees(matrixValues[1]);
//double roll = Math.toDegrees(matrixValues[2]);
WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display mDisplay = mWindowManager.getDefaultDisplay();
Float degToAdd = 0f;
if(mDisplay.getRotation() == Surface.ROTATION_0)
degToAdd = 0.0f;
if(mDisplay.getRotation() == Surface.ROTATION_90)
degToAdd = 90.0f;
if(mDisplay.getRotation() == Surface.ROTATION_180)
degToAdd = 180.0f;
if(mDisplay.getRotation() == Surface.ROTATION_270)
degToAdd = 270.0f;
mapView.setFacingDirection((float) (azimuth + degToAdd)); //DEGREES NOT RADIANS
}
}