Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Processing Timed Keyboard Input

Author: Kurosh Fallahzadeh -- Published? true -- FormatLanguage: W

Problem:

To determine if a user generated message, like a key press/release, has occoured within a certain time interval. Useful in game input handling.

Solution:

Put the thread to sleep for the time interval and use a Handler to determine if key press/release has occoured

Discussion:

The interval is a long integer that represents time in milliseconds. When the user releases a key, we override the onKeyUp method to invoke our taskHandler methods, which basically continue to repeatedly execute task A as long as the user continues to press/release any key within the 1 second interval, else executes task B

private long interval = 1000; // 1 second time interval

private taskHandler myTaskHandler = new taskHandler();

class taskHandler extends Handler {

    @Override
    public void handleMessage(Message msg) {
    	MyMainClass.this.executeTaskB();
    }
    
    public void sleep(long timeInterval) {
      //remove previous keyboard message in queue
    	this.removeMessages(0);
        //enqueue current keyboard message to execute after timeInterval
        sendMessageDelayed(obtainMessage(0), timeInterval);
    }
};   


@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
          
//execute TaskA and call handler to execute TaskB if key release message arrives after 'interval' has elapsed
    executeTaskA();
    myTaskHandler.sleep(interval);

 return true;
}

public void executeTaskA() {
...
}

public void executeTaskB() {
...
}
No records found.