4

I'm developing a phonegap app based on jQuery mobile. I'm trying to put a button in my app, behaving like back button on android devices. I don't want just a history.back(), but I want the exactly same behavior, means going back when no handler is attached, and performing the handler when one is attached to the event backbutton.

In other words, I want to simulate hardware back button, in software (exactly same behavior)

I've tried these codes, with no success:

$("#backbtn").click(function(){
    var backButtonEvent = document.createEvent('Events');
    backButtonEvent.initEvent('backbutton', false, false);
    document.dispatchEvent(backButtonEvent);
});

What can I do?

Ahmad
  • 5,551
  • 8
  • 41
  • 57
  • check this link... http://stackoverflow.com/questions/9631933/override-android-backbutton-behavior-only-works-on-the-first-page-with-phonegap – Banik Mar 03 '16 at 10:06
  • @Banik This is not related to my problem – Ahmad Mar 03 '16 at 10:24
  • you have to programmatically trigger the native method... just posted an answer try this... – Banik Mar 03 '16 at 10:38

2 Answers2

0

import javascriptinterface package in mainActivity class

import android.webkit.JavascriptInterface;

add JavaScript interface in onCreate method in the MainActivity Class

super.appView.addJavascriptInterface(new JSInterface(), "sampleproj");

Then define the javascript Interface

public class JSInterface{
       @JavascriptInterface
       public void dispachBackKey() {
            dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
            dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
       }
}

Now call the native method in javascript

window.sampleproj.dispachBackKey();
Banik
  • 911
  • 6
  • 10
  • I've tried your solution, with some modifications. First, I had to import `android.view.KeyEvent` too. Second, I had to use `(WebView)appView.getEngine().getView()` instead of `super.appView`. At last, when I executed `sampleproj.dispachBackKey()` is JS, I got some errors: `Uncaught Error: Java exception was raised during method invocation at Error (native) at :2:13 at Object.InjectedScript._evaluateOn (:895:140) at Object.InjectedScript._evaluateAndWrap (:828:34) at Object.InjectedScript.evaluate (:694:21)` – Ahmad Mar 03 '16 at 11:03
-1
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady(){
    var backButtonElement = document.getElementById("backbtn");
    backButtonElement .addEventListener("click", buttonCallBack, false);
}

function buttonCallBack(){
    document.addEventListener("backbutton", onBackButton, false);
}
function onBackButton(){
   // write your stuff
}

Try the above code it will work

Naresh Kumar
  • 938
  • 5
  • 12