Android Cordova backbutton event Not triggering

643 views Asked by At

I'm using "backbutton" event of Cordova (version 6.3.2) in my Android app. But when the back button is clicked, the app closes instead of triggering the backbutton event. There are many similar questions but I had to ask again as nothing helped me.

My Init Script :

  var cordovaInit = function (){

    //To bootstrap the app manually once the device is ready
    var receivedEvent = function (){
        angular.bootstrap($('body'), ['myModule']);
    };


    var onDeviceReady = function (){            
      console.log("Device Ready");
      receivedEvent('deviceReady');
      document.addEventListener("backbutton", function(e){
               // My Code here
      });
    };

    //call onDeviceReady when the device is ready
    this.bindEvents = function (){
        document.addEventListener('deviceReady', onDeviceReady, false);
    };

    //If cordova is present, wait for it to initialize, otherwise just try to
    //bootstrap the application.

    if(window.cordova !== undefined){
        this.bindEvents();
    }
    else{
        receivedEvent();
    }
  };

   $(function (){
     new cordovaInit();
   });

As you can see above that I'm registering the event after the deviceReady event and the deviceReady event is working fine. Any help is very much appreciated. Thanks in advance.

2

There are 2 answers

1
Sam On

I think what might be happening is your app has one screen and when the back button is pressed it quits the app. You need to prevent the default back behavior. Try adding this line inside the back button event:

e.preventDefault();
0
Tom On

Had the problem too. For me the issue was in eclipse. When I built the app using cordova command line and downloaded the apk to an Android device, it worked fine.

In eclipse I had other projects with former versions of Cordova. As a class CordovaLib already existed, Eclipse didn't import the new one from the new project, which was wrong. Then I edited properties of the new project and - also wrong! - added the existing (old) CordovaLib under "Android" -> Library.

The correct way instead is to import the new CorodovaLib together with the project, rename it during import (attention: on Mac you must blur the name field to make eclipse recognize the renaming. if you click 'import' with the cursor still in the name field the new name is beging ignored during import) to avoid a name conflict with the older CordovaLib class. So at the project's properties -> Android -> Library the new version of CordovaLib should be included.