Reputation: 3940
I am developing a HTML5 web-application and compiling it with Cordova (phonegap) 1.7.
I want to override the Android backbutton so that I can call window.history.back() instead of closing the application (default Android). How can I prevent Android from killing the defaultactivity on back button pressed?
I get the "Back button pressed!!!!" in logcat, so the method is fired before the application is closed.
This is what I have so far:
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
document.addEventListener("backbutton", function(e) {
console.log("Back button pressed!!!!");
window.history.back();
}, false);
}
EDIT: I am willing to accept an answer explaining a way to simulate the window.history.back() directly from the DefaultActivity.java android class if that is possible!
Upvotes: 4
Views: 4710
Reputation: 3940
I solved my own question by adding the code below to the DefaultActivity.java
file to prevent the default android behavior, and keeping the JavaScript code as stated in the question:
@Override
public void onBackPressed() {
return;
}
I hope this helps someone in the future with the same problem!
Upvotes: 6
Reputation: 21
I took this approach. I hooked the backbutton event as you have shown. I look to see if this is the first page or not and then ask the user if they want to exit the program or not. This depends on what you want your program to do depending on its state. I did not add the override as you have shown; I didnot seem to need it.
if ($.mobile.activePage.attr('id') === 'firstpage') {
// Prompt to confirm the exit
} else {
window.history.back();
}
If they want to exit you can call:
navigator.app.exitApp();
to close your program.
I imagine you still want to allow the user to exit your app. I don't tend to use apps that do not allow an exit of some kind.
Hope this helps you out.
Upvotes: 2
Reputation: 3755
Never had to do that but, have you tried to return true
?
Like in the Java SDK, if you return True
, the system will assume you have correctly catched the event and will no longer pass it to other event listeners.
Upvotes: 0