开发者

Android: light weight solution to detect keypress

开发者 https://www.devze.com 2023-01-12 13:10 出处:网络
In Android I am writing an application in which, I would like to capture an event if in case user doesn\'t do any activity (tapping/key press).

In Android I am writing an application in which, I would like to capture an event if in case user doesn't do any activity (tapping/key press).

For better context - It is like session ti开发者_如何学Gomeout.

Basic solution - I can override the key press/tapping event and put one timer which continuously run either as thread or service. In my opinion this is bit heavier solution in terms of resource.

Any thoughts for elegant solution?


Activity class fields:

private static final int KEY_TIMEOUT = 60000;
private long lastKeyEventTime;
private boolean checkKey;

in Activity.onCreate() :

checkKey = true;

Thread t = new Thread(){
    while (checkKey){
        if (lastKeyEventTime!=0 && System.currentTimeMillis()-lastKeyEventTime>TIMEOUT){
            // TIMEOUT
        }

        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
    }
}
t.start();

in Activity.onDestroy():

checkKey = false;

in Activity.onKeyDown():

lastKeyEventTime = System.currentTimeMillis();
0

精彩评论

暂无评论...
验证码 换一张
取 消