Freeze screen orientation

android, android-screen, screen-orientation

Solution

So, here is my solution.

private int getCurentOrientation() {
    Display d = ((WindowManager) getSystemService(WINDOW_SERVICE))
            .getDefaultDisplay();
    boolean isWide = d.getWidth() >= d.getHeight();
    switch (d.getRotation()) {
    case Surface.ROTATION_0:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    case Surface.ROTATION_90:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
    case Surface.ROTATION_180:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
    case Surface.ROTATION_270:
        return isWide ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }
    return -1;
}

private void lockOrientation(boolean lock) {
    if (lock) {
        setRequestedOrientation(getCurentOrientation());
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
    }
}

On 4 devices (2 smartphones and 2 tablets) it works as nedded.

Problem

There is CheckBox with following code: ``` CheckBox cb = (CheckBox)findViewById(R.id.freezer); cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); } } }); ``` So, when i check it, screen is rotated to default system orientation (landscape for my tablet). I need to freeze CURRENT orientation. If you turned device to portrait and toggled CheckBox, device rotation must be ingored until CheckBox is unchecked. Display.getRotation() is not a solution, because each device has it's own Surface.ROTATION

Original source

Related problems