Search code examples
javaandroidcordovacordova-plugins

Prevent the back button from quitting android app inside a Cordova plugin


I am creating a Cordova plugin based on the Android Camera2Video example: http://developer.android.com/samples/Camera2Video/index.html

My plugin code is working here: https://github.com/kmturley/cordova-plugin-media-custom

When I press the Android back button within the WebView I can successfully control it's behaviour using the following JavaScript code:

document.addEventListener('backbutton', function (e) {
    e.preventDefault();
    window.alert('back pressed');
}, false);

However when I press the same back button while the native plugin overlay is shown, the JavaScript is ignored and the app quits.

How can I catch the back button event and use it to trigger my plugin hide() method?

Here is a link to the Cordova code handling the JavaScript back button: https://github.com/apache/cordova-android/blob/4bf705a3d39b34400388265381a9975b246e3779/framework/src/org/apache/cordova/CoreAndroid.java#L231 https://github.com/apache/cordova-android/blob/4bf705a3d39b34400388265381a9975b246e3779/framework/src/org/apache/cordova/CordovaWebViewImpl.java#L549


Solution

  • In your activity, override the method onBackPressed(). It is called when user taps on Back button.