Reputation: 366
In my Business card reader application, I fixed screen orientation in my first camera capture activity, now I want to know orientation is landScape or portrait. I use SensorManager but it will give most of time landscape when just small change angle of mobile.
here screenOrientation=0 when Landscape
and screenOrientation=1 when Portrait
private void registerAccelerometerSensor() {
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_SENSOR_ACCELEROMETER)) {
eventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.values[1] < 6.5 && event.values[1] > -6.5) {
if (orientation != 1) {
Log.d("Sensor", "Landscape");
screenOrientation = 0;
}
} else {
if (orientation != 0) {
Log.d("Sensor", "Portrait");
screenOrientation = 1;
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
sensorManager.registerListener(eventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
} else {
screenOrientation = -1;
}
}
Upvotes: 1
Views: 395
Reputation: 10368
See some sample code here:
public int getScreenOrientation() {
int rotation = getWindowManager().getDefaultDisplay()
.getRotation();
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_270) {
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
} else {
return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
}
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_90) {
return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else {
return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}
}
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
Upvotes: 1