1

According to android documentation, detecting key release should be as simple as:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    System.out.println("pressed");
    event.startTracking();
    return true;
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    System.out.println("released");
    return true;
}

but when trying to implement it, it doesn't work as expected.

I need to detect when a key of a bluetooth keyboard is pressed and receive only one call to onKeyDown when that happens, and detect when that same key is released. I'm I doing something wrong, or is there any other way to get this desired result?

When pressing and holding down any key, I get this repeatedly on console:

I/System.out: pressed
I/System.out: released
I/System.out: pressed
I/System.out: released
I/System.out: pressed
I/System.out: released
I/System.out: pressed
I/System.out: released

Thanks.

RodrigoFranco
  • 63
  • 1
  • 9
  • "it doesn't work as expected" -- you might wish to explain, in detail, what you are expecting and what results you are getting. For example, what exactly are the "many calls while it's pressed"? – CommonsWare Nov 09 '16 at 00:19
  • when i press a key and keep it pressed, i get repeatedly: I/System.out: pressed, I/System.out: released. I expect it to cal "pressed" once when I press it, and "released" when release it, instead, "pressed" and "released" are call repeatedly all time while I'm pressing any given key... – RodrigoFranco Nov 09 '16 at 00:43
  • Try returning `false` from both methods. – CommonsWare Nov 09 '16 at 00:48
  • Done, but the same happens... – RodrigoFranco Nov 09 '16 at 00:50
  • Is there anything unusual about this keyboard? If this is a non-keyboard device that pretends to be a Bluetooth keyboard for Android integration, you might try repeating your tests with a more traditional Bluetooth keyboard, to see if the problem is more with the Bluetooth device vs. Android. I haven't played with `startTracking()`, so I don't know if that is having an impact. – CommonsWare Nov 09 '16 at 00:55
  • It's an apple bluetooth keyboard – RodrigoFranco Nov 09 '16 at 00:56

1 Answers1

0
Use OnTouchListener instead of OnClickListener:

// this goes somewhere in your class:
  long lastDown;
  long lastDuration;

  ...

  // this goes wherever you setup your button listener:
  button.setOnTouchListener(new OnTouchListener() {
     @Override
     public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
           lastDown = System.currentTimeMillis();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
           lastDuration = System.currentTimeMillis() - lastDown;
        }
     }`enter code here`
  });