3

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.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
user3555472
  • 836
  • 3
  • 11
  • 38

3 Answers3

10

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

Ishtiaq
  • 1,206
  • 9
  • 18
  • great answer, but is possible to know the position of the back button (if is on the right or left)? I want to highlight it with an arrow. If it's software maybe is version check, but if physical I really don't know – Giudark Sep 28 '16 at 23:23
  • what if the device is using a rom that enables the software keys even when they got the HW ones? Examples are CM, LOS, OxygenOS and so on – Lamberto Basti Mar 24 '17 at 16:17
0

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();
}
Fangming
  • 24,551
  • 6
  • 100
  • 90
Pankaj Arora
  • 10,224
  • 2
  • 37
  • 59
-2

You can do this by overriding the method

   @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }
Rishabh Bhardwaj
  • 832
  • 8
  • 20