Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing back key press on PhoneGap for Android

I am using PhoneGap for Android Application development and I'm stuck at capturing the back key press on the device! I tried everything from other threads and from the official wiki page but none seem to work! :(

I could capture menu and search keys with keyEvent.menuTrigger and keyEvent.searchTrigger but can't seem to capture the back button press! I tried keyEvent.backTrigger similarly but it didn't work! Adding event listener for 'backKeyDown' event doesn't work either!

Here's my code:

BackButton.override();
    document.addEventListener('backKeyDown', function(e) {
  console.log('Caught it!');
}, false);
keyEvent.searchTrigger= searchPressed;
keyEvent.menuTrigger=menuPressed;
keyEvent.backTrigger=backPressed;

The console says:

Line 1 : Uncaught TypeError: Cannot call method 'backTrigger' of undefined

Doesn't that mean something.backTrigger() is being called but the object something doesn't exist. What is that something? Or is there any way around?

Tried the same with KeyEvent too, with no luck! Please help!

Thanks in advance! :)

like image 223
xtranophilist Avatar asked Apr 18 '11 05:04

xtranophilist


2 Answers

PhoneGap Wiki page about Android button handler has been updated for PhoneGap 0.9.5 :

// 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!');
}

Works for me with PhoneGap 0.9.6

You can also handle others buttons with menubutton and searchbutton events.

like image 172
Reborn Avatar answered Sep 23 '22 10:09

Reborn


if you are using api level above 2.0 then u can override following function

@Override
public void onBackPressed() {
// do something on back.
return;
}

for tracking back button pressed event.

if not then you can override onKeyDown event of activity and track back button

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        return true;
    }

    return super.onKeyDown(keyCode, event);
} 
like image 36
Sunil Pandey Avatar answered Sep 21 '22 10:09

Sunil Pandey