Android Press again to return to exit the program - the return key, menu key events overwrite

Junior partner played the game knows that now almost all of the game will pop a reminder when you want to quit, such as shown below:
Here Insert Picture Description

So this is how to achieve it? Let's take a closer look!

The first wave of my renderings
Here Insert Picture Description

The most important thing is to understand the function realization of ideas, like the game exit confirmation function, you need to rewrite the return key events, the return of the original key event into a pop-Dialog, and then deal with two-button click event Dialog, such as canceled button directly to the Dialog pop canceled, determined to exit the program, and so on ...

Directly on the code:

Here is Ctrl + O, rewrite Activity of the event, here are rewritten onKeyDown event, and then use an if statement to return to the menu key events and key events to be rewritten, and finally must pay attention to return true;prevent the execution of the event after you rewrite go-set to return to the event! (I wrote here just a simple setText () event for demonstration)

And the little fellow would certainly think overwrite events HOME key, after Android4.0, for the safety of users, Google has been rewritten for HOME incident made a safe treatment, and then need to be rewritten if more trouble, need to use the radio, follow-up I will write a separate blog HOME key event!

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Android4.0 开始 为了安全,对于HOME事件的改写失效
        if (keyCode==KeyEvent.KEYCODE_BACK){
            /** 这个是再按一次返回的代码示例
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次返回主页", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }*/
            mTxvKeycode.setText("按了返回");
            //对事件进行终止,防止再调用正常的Back事件
            return true;
        }else if (keyCode==KeyEvent.KEYCODE_MENU){
            mTxvKeycode.setText("按了菜单");
            return true;
        }else{
            return super.onKeyDown(keyCode, event);
        }
    }

Thanks for reading!

Published 42 original articles · won praise 303 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_44720366/article/details/105163095