How to detect Hard/Soft back button on Android device?

不羁岁月 提交于 2019-12-23 18:46:24

问题


I want to know how to detect hard or soft "BACK Button" on device? I searched but mostly I found this code

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

But I just need to detect if there is BACK button exist on device or not in form of hard or soft.


回答1:


I think this should work

Queries the framework about whether any physical keys exist on the any keyboard attached to the device that are capable of producing the given key code.

boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);

Android developer documentation




回答2:


the best way is to overide the onBackPress(),becuase whatever the functionality you want to achieve onBackpress key event,you can also do that in onBackPress() method.

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
   // do your stuff  here
    super.onBackPressed();
}



回答3:


You can do this by overriding the method

   @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }


来源:https://stackoverflow.com/questions/24358645/how-to-detect-hard-soft-back-button-on-android-device

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