I had to detect screen orientation changes, but my activity in the manifest file had to stay locked in android:screenOrientation="portrait"
mode.
This way i was not able to use onConfigurationChanged
. I had to monitor the sensor manager.
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationSensor;
private static final int SENSOR_DELAY = 500 * 1000; // 500ms
private static final int FROM_RADS_TO_DEGS = -57;
private String oldtilt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mSensorManager = (SensorManager) getSystemService(Activity.SENSOR_SERVICE);
mRotationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mSensorManager.registerListener(this, mRotationSensor, SENSOR_DELAY);
} catch (Exception e) {
Toast.makeText(this, "Hardware compatibility issue", Toast.LENGTH_LONG).show();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor == mRotationSensor) {
if (event.values.length > 4) {
float[] truncatedRotationVector = new float[4];
System.arraycopy(event.values, 0, truncatedRotationVector, 0, 4);
update(truncatedRotationVector);
} else {
update(event.values);
}
}
}
private void update(float[] vectors) {
float[] rotationMatrix = new float[9];
SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);
int worldAxisX = SensorManager.AXIS_X;
int worldAxisZ = SensorManager.AXIS_Z;
float[] adjustedRotationMatrix = new float[9];
SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisX, worldAxisZ, adjustedRotationMatrix);
float[] orientation = new float[3];
SensorManager.getOrientation(adjustedRotationMatrix, orientation);
float pitch = orientation[1] * FROM_RADS_TO_DEGS;
float roll = orientation[2] * FROM_RADS_TO_DEGS;
// Log.v("Pitch + Roll", Float.toString(pitch) + " " + Float.toString(roll) );
String newtilt;
if ( -40<pitch && pitch<40 ){
if (60<roll && roll<120){
newtilt="left";
if (!newtilt.equals(oldtilt)){
oldtilt = newtilt;
Log.v("tilt",newtilt);
}
}else if(-120< roll && roll<-60){
newtilt="right";
if (!newtilt.equals(oldtilt)){
oldtilt = newtilt;
Log.v("tilt",newtilt);
}
}else if(-45 < roll && roll< 45){
newtilt="portrait";
if (!newtilt.equals(oldtilt)){
oldtilt = newtilt;
Log.v("tilt",newtilt);
}
}
}
}
}
This code snippet is based on the code of William J. Francis a great developer at TechRepublic.
Full sample app can be found at: http://www.techrepublic.com/article/pro-tip-use-android-sensors-to-detect-orientation-changes
Cheers!