iOS: shouldAutorotateToInterfaceOrientation / Lock Orientation in PhoneGap

Starting in PhoneGap 0.9.5 there’s an undocumented iOS only feature that allows you to handle whether the device should rotate to a particular orientation. It exposes the iOS Objective-C method shouldAutorotateToInterfaceOrientation with a JavaScript function shouldRotateToOrientation.

function shouldRotateToOrientation (rotation) {
    switch (rotation) {
        //Portrait or PortraitUpsideDown
        case 0:
        case 180:
            return true;
        //LandscapeRight or LandscapeLeft
        case 90:
        case -90:
             return false;
    }
}

This needs to be in the global scope of your JavaScript and will get called before any rotations occur, so keep it lean to avoid locking up the UI. Returning true allows the device to rotate, returning false prevents it.

Works great in your HTML5 iOS, iPhone and iPad apps, sadly currently there’s no Android or other platform integration. Hopefully we’ll see a cross-platform method soon!

PhoneGap & The Android Back Button (0.9.5)

In PhoneGap 0.9.5 they’ve updated how the Android back button works. Here’s what to change.

Before in 0.9.4:

BackButton.override();
document.addEventListener("backKeyDown", function() {
    someBackButtonHandlingFunction();
}, true);

Now in 0.9.5:

document.addEventListener("backbutton", function() {
    someBackButtonHandlingFunction();
}, true);

In 0.9.5 and later you no longer need to override the back button, as it’s assumed when you’re adding the event listener that you want to handle the button yourself. Make sure if the user is at the root view of your mobile app, the back button closes the app.

To exit the app in 0.9.4 you’d use:

BackButton.exitApp();

Now, in 0.9.5 you need to use:

device.exitApp();

Good to see PhoneGap advancing to a more device agnostic syntax.