This little bit of code is going to be useful to those of you developing a “singe page” app inside of PhoneGap. This applies to Sencha Touch (big fan), but doesn’t as much to jQuery mobile and jQTouch, as it’s a multi-page/navigation based event framework (it uses the app’s url string to do things like move around to different link anchors). This is really important on these single page apps because the Android hardware back button will send the PhoneGap app to the background. You need some way to intercept it so you can start building your own history management mechanism. Sounds fun, right? It’s actually not that hard.
On app initialization, add an event listener for Android’s back button, and the callback to handle it. PhoneGap takes care of the interface between Android and your app.
1 2 3 4 5 |
document.addEventListener("backbutton", backKeyDown, true); function backKeyDown() { // Call my back key code here. alert('go back!'); } |
That’s enough to get you started, and it should be pretty apparent if it works or not.
How about history management? It will depend on the app and what makes sense, BUT you’ll probably want to create a history array, and pop off some value that directs the app each time you hit the hardware back button. Here’s another idea: change the destination of the back button depending on the view. I personally like the idea of the latter because apps built on Sencha Touch are going to have easy tie-ins through predefined listeners JS Objects that define screen elements like buttons.