Back Button Usage

Philipp Gildein edited this page Aug 10, 2014 · 5 revisions

Android

PhoneGap 0.9.5 to Latest

// This is your app's init method. Here's an example of how to use it
function init() {
    document.addEventListener("deviceready", onDR, false);
} 
function onDR(){
    document.addEventListener("backbutton", backKeyDown, true);
    //boot your app...
}
function backKeyDown() { 
    // do something here if you wish
    // alert('go back!');
}

PhoneGap 0.9.4 and Earlier

// This is your app's init method. Here's an example of how to use it
function init() {
    document.addEventListener("deviceready", onDR, false);
}
function onDR(){
    BackButton.override(); 
    document.addEventListener("backKeyDown", backKeyDown, true);
    //boot your app...
}
function backKeyDown() { 
    // do something here if you wish
    // alert('go back!');
}

Note

If you have the problem, that back button always exits the app after firing the event, add the following to your AndroidManifest.xml:

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15"  />

Tips

  • If you're working with a single page architecture, and you're handling the back button yourself (that is, a framework isn't handling it for you), it's probably best to implement a global handler that can work across the app. It's tempting to create a handler when a view is displayed, and then delete the handler when the view is removed, but this can often result in some strange behavior, including: Multiple backbutton events firing at unexpected times, Unexpected exiting of the app, and more.
  • Be sure to handle double-bouncing -- that is, if the user double-taps the back button quickly, what do you do? If you have animations in progress, you may corrupt your view hierarchy, create odd visual glitches, etc. It would be a wise idea to record the time of the last press, and if the time between the last and present press is too short, one should ignore the second press.
  • If implementing a global handler, and you want the expected behavior of exiting the app when at the top of the information hierarchy, you can use navigator.app.exitApp();

Avoiding the Accidental Exit

Often the result of a back button event at the top of the information hierarchy would result in the immediate exit of the app. Sometimes this behavior is not wanted. Some patterns you can use to help avoid accidental exits:

  • Ignore the back button event. In this case, the back button cannot exit the app. If you do this, you should provide an alternative exit method.
  • Prompt the user if they are certain they wish to exit.
  • Require a second back button event to exit. If you follow this approach, you should probably raise a toast to indicate to the user that a second press is required in order to exit the app.