I'm trying to listen to an android hardware button to manually cancel a countdown timer.
I have looked around, the solution seems to be to override the "onKeyUp" or "onKeyDown" for the buttons. The problem is I think I can only write the override method for the activity class or UI elements. However, I don't know how to listen to such hardware key events from a Java inner class.
In my current implementation, where the override method is randomly put in my activity, the cancelation of my timer object is executed infinitely...
Please help!
EDIT: I did as suggested: moved the listener to the current focus. I call this method from onTick method of my timer class. But still no luck. the debugger shows that the overriden method is never called. in my app still the button clicks result in volume up/down.
public void getVolBtnEvent(){
parent.setOnKeyListener(new View.OnKeyListener() {
@SuppressWarnings("unused")
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP || event.getKeyCode()== KeyEvent.KEYCODE_VOLUME_UP)
volBtnClicked++;
if (volBtnClicked ==1){
if (currentV ==1 && MyConstants.RHYTHM_WITH_VOL_BTN)
processTouchEventR();}
else if (volBtnClicked ==2){
if (currentV ==1 && MyConstants.RHYTHM_WITH_VOL_BTN) {
stopTimerR();
parent.setEnabled(false);
writeToFile ("blah");
getConfirmation();
}
}
return true;
}// end of onkey
});
}//end of getVolbtn
This simply can't be done because a timer class runs the method for a small number of milliseconds, and the chances that one instance of my button click is happening at the exact same amount of time is very low....