Cordova for android如何在App中處理退出按鈕事件

來源:互聯網
上載者:User

標籤: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中處理退出按鈕事件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.