项目须要在HTML5 Android App中增加对返回键的处理,发现直接在Activity中加返回键处理代码不起作用,分析cordova源代码发现返回键已经被WebView处理掉了,所以仅仅能在js中处理返回键了!
@Override public 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); } }在继承了CordovaActivity的Activity中,上面的代码是不会起作用的,由于WebView已经处理了返回键事件,并退出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); }CordovaActivity源代码中的返回键处理代码
以下的代码能够响应后退button,并提示用户再次点击才退出。
假设3秒后没有点击则又一次注冊事件。
注意:window.plugins.ToastPlugin.show_short()是显示toast消息的插件!
代码:
// 等待载入PhoneGap document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap载入完成 function onDeviceReady() { //按钮事件 document.addEventListener("backbutton", eventBackButton, false); //返回键 document.addEventListener("menubutton", eventMenuButton, false); //菜单键 document.addEventListener("searchbutton", eventSearchButton, false); //搜索键 } //返回键 function eventBackButton(){ //confirm("再点击一次退出!"); window.plugins.ToastPlugin.show_short('再点击一次退出!'); document.removeEventListener("backbutton", eventBackButton, false); //注销返回键 //3秒后又一次注冊 var intervalID = window.setInterval( function() { window.clearInterval(intervalID); document.addEventListener("backbutton", eventBackButton, false); //返回键 }, 3000 ); } //菜单键 function eventMenuButton(){ window.plugins.ToastPlugin.show_short('点击了 菜单 按钮!'); } //搜索键 function eventSearchButton(){ window.plugins.ToastPlugin.show_short('点击了 搜索 按钮!'); }