@panavtec 对 API 23 的回答的翻译,以此作为参考
class MyActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private float[] lastMagFields = new float[3];;
private float[] lastAccels = new float[3];;
private float[] rotationMatrix = new float[16];
private float[] orientation = new float[4];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
}
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, lastAccels, 0, 3);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, lastMagFields, 0, 3);
break;
default:
return;
}
if (SensorManager.getRotationMatrix(rotationMatrix, null, lastAccels, lastMagFields)) {
SensorManager.getOrientation(rotationMatrix, orientation);
float xAxis = (float) Math.toDegrees(orientation[1]);
float yAxis = (float) Math.toDegrees(orientation[2]);
int orientation = Configuration.ORIENTATION_UNDEFINED;
if ((yAxis <= 25) && (yAxis >= -25) && (xAxis >= -160)) {
Log.d(TAG, "Portrait");
orientation = Configuration.ORIENTATION_PORTRAIT;
} else if ((yAxis < -25) && (xAxis >= -20)) {
Log.d(TAG, "Landscape Right");
orientation = Configuration.ORIENTATION_LANDSCAPE;
} else if ((yAxis > 25) && (xAxis >= -20)){
orientation = Configuration.ORIENTATION_LANDSCAPE;
Log.d(TAG, "Landscape Left");
}
}
}
}