Wednesday, April 24, 2013

Windows 8 Orientation Check

Ideally we would like to restrict rotation for some specific pages in a Windows 8 mobile app. For example, always show landscape mode for one page and portrait mode for another page. This is super simple in Android where we can configure an activity's screen orientation in AndroidManifest.xml file or set it through code. After some research, unfortunately I found it's impossible doing such simple thing in Windows 8.

As a workaround we display a warning message on the screen when the orentation is not in desired mode. First I tried OrientationSensor :

    var orientationSensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault();
    if (orientationSensor) 
        orientationSensor.addEventListener("orientationchanged", onCameraOrientationChanged);
The event is set in a few pages not globally, but I found the event is not reliable and it's not fired sometimes when the screen is rotated. So I go back to the "resize" event and it always works:
    window.addEventListener("resize", orientationCheck);
    function orientationCheck() {
        var isOnCertainPage = 0; // Check if it's current page
        if (isOnCertainPage) { 
            if (Windows.UI.ViewManagement.ApplicationView.value != 
               Windows.UI.ViewManagement.ApplicationViewState.fullScreenLandscape) {
                // Show warning message 
            }
        }
    }