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

Processing Timed Keyboard Input

Published? true
FormatLanguage: WikiFormat


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


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


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 {

    public void handleMessage(Message msg) {
    public void sleep(long timeInterval) {
      //remove previous keyboard message in queue
        //enqueue current keyboard message to execute after timeInterval
        sendMessageDelayed(obtainMessage(0), timeInterval);

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

 return true;

public void executeTaskA() {

public void executeTaskB() {