Android – Bloqueando a orientação de tela programaticamente

full_screen_android

Segue alguns métodos uteis para lidar com a orientação de tela programaticamente.

/**
 * Destravando orientação de tela
 *
 */
public static boolean releaseScreenOrientation(Activity activity) {
    return lockScreenOrientation(activity, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}

/**
 * Travando orientação de tela na posição atual.
 *
 */
public static boolean lockCurrentScreenOrientation(Activity activity) {
    return lockScreenOrientation(activity, activity.getRequestedOrientation());
}

/**
 * Recebe como parametro: ActivityInfo.SCREEN_ORIENTATION_XXXXXX
 *
 * @param activity Activity
 * @param screenOrientation ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
 */
public static boolean lockScreenOrientation(Activity activity, int screenOrientation) {
    activity.setRequestedOrientation(screenOrientation);
    return true;
}

/**
 * Recebe como parametro: Surface.ROTATION_X
 *
 * @param activity Activity
 * @param screenRotation Surface.ROTATION_0 / 90 / 180 / 270
 */
public static boolean lockScreenRotation(Activity activity, int screenRotation) {
    if (screenRotation > -1) {
        int orientation = activity.getRequestedOrientation();
        switch (screenRotation) {
            case Surface.ROTATION_0:
                orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                break;
            case Surface.ROTATION_90:
                orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                break;
            case Surface.ROTATION_180:
                orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
                break;
            case Surface.ROTATION_270:
                orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
                break;
        }
        return lockScreenOrientation(activity, orientation);
    } else {
        return false;
    }
}