this methods can detect (and) set orientation:
getResources().getConfiguration().orientation
and
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
I'm using those methods to catch all orientations:
inside onCreate
:
initOrientation();
where
private void initOrientation() {
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mLastRotation = mWindowManager.getDefaultDisplay().getRotation();
myOrientationEventListener
= new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI){
@Override
public void onOrientationChanged(int orientation) {
// Log.d(TAG, "ORIENTATION: " + orientation);
Display display = mWindowManager.getDefaultDisplay();
int rotation = display.getRotation();
if (((rotation == Surface.ROTATION_90 && mLastRotation == Surface.ROTATION_270)
|| (rotation == Surface.ROTATION_270 && mLastRotation == Surface.ROTATION_90)
|| (rotation == Surface.ROTATION_0 && mLastRotation == Surface.ROTATION_180)
|| (rotation == Surface.ROTATION_180 && mLastRotation == Surface.ROTATION_0))) {
//if ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && rotation != mLastRotation) {
Log.i(TAG, "changed >>> " + rotation + " :: " + _.mWidth);
// do something
mLastRotation = rotation;
}
}
};
if (myOrientationEventListener.canDetectOrientation()){
Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show();
myOrientationEventListener.enable();
}
else{
Toast.makeText(this, "Can't DetectOrientation", Toast.LENGTH_LONG).show();
// finish();
}
}
it depends on what your really want to realize. the method above can detect portrait>portrait and landscape>landscape shifts.
In order to force lock and release rotation I'm using this approach:
protected void mLockScreenRotation(int i)
{
// Stop the screen orientation changing during an event
switch (i)
{
default:
case 0:
switch (this.getResources().getConfiguration().orientation)
{
case Configuration.ORIENTATION_PORTRAIT:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case Configuration.ORIENTATION_LANDSCAPE:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
case 1:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case 2:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
}
mLockScreenRotation(0)
- locks