How does Cordova for android process exit button events in the App?
The project needs to add the processing of the Return key to the HTML5 Android App. It is found that adding the return key directly to the Activity does not work. After analyzing the cordova source code, it is found that the return key has been processed by WebView, so we can only process the return key in js!
@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK) {if (exit > 1) {finish();} else {Toast.makeText(this, R.string.toast_exit, Toast.LENGTH_SHORT).show();exit++;}return true;} else {return super.onKeyDown(keyCode, event);}}
In the Activity that inherits CordovaActivity, the above Code does not work, because WebView has handled the return key event and exited the Activity.
/* * Android 2.x needs to be able to check where the cursor is. Android 4.x does not * * (non-Javadoc) * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent) */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Determine if the focus is on the current view or not if (appView != null && appView.getFocusedChild() != null && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) { return appView.onKeyDown(keyCode, event); } else return super.onKeyDown(keyCode, event); }
Return key processing code in CordovaActivity source code
The following code responds to the back button and prompts the user to click again to exit.
If you do not click it three seconds later, the event will be re-registered.
Note: window. plugins. ToastPlugin. show_short () is a plug-in that displays the toast message!
Code:
// Wait for loading PhoneGapdocument. addEventListener ("deviceready", onDeviceReady, false); // The function onDeviceReady () {// button event document after the PhoneGap is loaded. addEventListener ("backbutton", eventBackButton, false); // return key document. addEventListener ("menubutton", eventMenuButton, false); // menu key document. addEventListener ("searchbutton", eventSearchButton, false); // search key} // return key function eventBackButton () {// confirm ("Click again to exit! "); Window. plugins. ToastPlugin. show_short ('click again to exit! '); Document. removeEventListener ("backbutton", eventBackButton, false); // cancel the return key // register var intervalID = window after 3 seconds. setInterval (function () {window. clearInterval (intervalID); document. addEventListener ("backbutton", eventBackButton, false); // return key}, 3000);} // menu key function eventMenuButton () {window. plugins. toastPlugin. show_short ('click the menu button! ');} // Search key function eventSearchButton () {window. plugins. ToastPlugin. show_short (' click the search button! ');}