代码之家  ›  专栏  ›  技术社区  ›  Rajnikant

Android:检测按键的轻量级解决方案

  •  0
  • Rajnikant  · 技术社区  · 15 年前

    为了更好的上下文-这就像会话超时。

    基本解决方案-我可以覆盖按键/轻敲事件,并将一个计时器作为线程或服务连续运行。在我看来,从资源的角度来说,这是一个更重的解决方案。

    有什么好主意吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   plugmind    15 年前

    活动类字段:

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

    在活动.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();
    

    在活动.onDestroy():

    checkKey = false;
    

    lastKeyEventTime = System.currentTimeMillis();