標籤:cordova android webview backkey
項目需要在HTML5 Android App中加入對返回鍵的處理,發現直接在Activity中加返回鍵處理代碼不起作用,分析cordova源碼發現返回鍵已經被WebView處理掉了,所以只能在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);}}在繼承了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('點擊了 搜尋 按鈕!');}
Cordova for android如何在App中處理退出按鈕事件