Sunday, March 31, 2019

android - How to differentiate between long key press and regular key press?

I'm trying to override the functionality of the back key press. When the user presses it once, I want it to come back to the previous screen. However, when the back key is long-pressed (for, let's say, two seconds or more), I want to exit the application.



By now, I have overriden these two methods in my activity:



@Override
public boolean onKeyDown( int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {

//manage short keypress
return true;
}
return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyLongPress( int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {
//manage long keypress (different code than short one)

return true;
}
return super.onKeyLongPress(keyCode, event);
}


But the onKeyLongPress callback is never called, because the event is always received by the onKeyDown method.



Is there any way of having both methods working? Or has it to be done all in the onKeyDown and use the number of repetitions/milliseconds to detect it?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...