Jump to content
COMFIED

Android Back Button (Cordova/ Phonegap)

Recommended Posts

I have built a web app using smart mobile studio and compiled to android APK on phonegap.

I'm trying to get the android back button to read a variable and either perform an action in the app or terminate the app.

The code below minimizes/ hides the android app, but doesn't terminate it.  How can I introduce a variable onBackKeyDown event and prevent app from minimizing?

 

Here is my code:

 

procedure TForm1.onDeviceReady;
begin
  receivedEvent('deviceready');
end;

 

procedure TForm1.bindEvents;
begin
     document.addEventListener('deviceready', onDeviceReady, false);

     asm
      document.addEventListener("backbutton", onBackKeyDown, false);
      function onBackKeyDown(e) {
      e.preventDefault();
}
     end;
...more code...

 

procedure TForm1.InitializeForm;
begin
  inherited;
   // this is a good place to initialize components

   bindEvents;
...more code...

Share this post


Link to post
Share on other sites
procedure TForm1.onBackKeyDown(eventObj: JEvent);
begin
  //Here do the right thing based on any variable in your app.
  //Call preventDefault if you do not want your app to close.
  eventObj.preventDefault();
end;

procedure TForm1.onDeviceReady(eventObj: JEvent);
begin
  document.addEventListener('backbutton', onBackKeyDown, false);
end;

procedure TForm1.bindEvents;
begin
  document.addEventListener('deviceready', onDeviceReady, false);
end;

Probably something like this.

Share this post


Link to post
Share on other sites

I have noted the problem - the event listener fires only once- on load, then ignores all events after that.

I am calling bindEvents in the InitializeForm;

Is there a way to listen to events as long as the app is running?

Edited by COMFIED

Share this post


Link to post
Share on other sites

DeviceReady is supposed to fire only once. That's where the example code I wrote sets the next event listener to listen to backbutton. That event listener should be active all the time when the app is running. Make sure that you don't set the backbutton-event listener before deviceready has happened.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×