How to disable all hardware keys programatically in android?

99封情书 提交于 2019-12-23 02:40:50

问题


I am developing android application with lock functionality. please suggest me how to disable all the hard keys programatically. here i am using beleow code to disable back button. i want like this functionality for all hard keys like home,search,camera, shortcut keys here is my code:

  @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                Log.d("KeyPress", "search");
                return true;
            }
            return false;
        }

Thanks in advance.


回答1:


Modify your onKey method to this :

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    return true;
}

When you return true from onKey method, it means that you have handled the key press yourself and prevents the OS from taking the default action. In you code, you are only handling the search button, but when you return true for all cases, it will block all buttons.

P.S this might not work for soft buttons. Refer this




回答2:


Try with this, it may solve your problem:

@Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KeyEvent.KEYCODE_HOME)) {
            System.out.println("KEYCODE_HOME");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            System.out.println("KEYCODE_BACK");
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_MENU)) {
            System.out.println("KEYCODE_MENU");
            return true;
        }
        return false;
    }


来源:https://stackoverflow.com/questions/13658567/how-to-disable-all-hardware-keys-programatically-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!