项目需要在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源码中的返回键处理代码
下面的代码可以响应后退按钮,并提示用户再次点击才退出。
如果3秒后没有点击则重新注册事件。
注意:window.plugins.ToastPlugin.show_short()是显示toast消息的插件!
代码:
// 等待加载PhoneGapdocument.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('点击了 搜索 按钮!');}
- 1楼offbye6小时前
- 终于找到原因了