【问题标题】:how to call key press using dispatchKeyEvent once per key press in android?如何在android中每次按键使用dispatchKeyEvent调用按键?
【发布时间】:2021-10-11 09:23:34
【问题描述】:

在下面的代码中,每次按下键码 144 时,我想在按键向下和向上之间的时间差大于 1000 毫秒时执行一些功能。但是我注意到,当 keydown 超过 100 毫秒左右时,它会继续重复调用 keydown,而不是等待 keyup 侦听器并最终计算差异,因为它计算与上次 keydown 时间的差异。如何以这样一种方式进行编程,即监听器应该只调用一次按键,直到触发kep up事件

@覆盖 public boolean dispatchKeyEvent(KeyEvent event) {

         long diff=0;

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                down = System.currentTimeMillis();
                Log.e("current_down",String.valueOf((down)));

                break;
            case MotionEvent.ACTION_UP:
                Log.e("current_down2",String.valueOf((down)));

                //this is the time in milliseconds
                diff = (System.currentTimeMillis()- down);
               


                break;
        }

        int keyCode = event.getKeyCode();
        Log.e("javan",String.valueOf((keyCode)));





        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == 144) {


          if(diff >1000){


            //do something 

  }
        }

【问题讨论】:

    标签: java android keypress


    【解决方案1】:
    long diff = 0; // these two values should be declared at the start of the
    long down = 0; // method
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if(down == 0) {
                down = System.currentTimeMillis(); // save current time if nothing is saved
                Log.e("current_down",String.valueOf((down)));
            }
            break;
        case MotionEvent.ACTION_UP:
            Log.e("current_down2",String.valueOf((down)));
    
            //this is the time in milliseconds
            diff = (System.currentTimeMillis()- down);
            down = 0; // if you need the value of down afterwards, 
                      // you can create another variable and save it there,
                      // this should be reset to 0 after action up for your case
    }
    

    现在,当然还有其他方法,但我想不到这个。

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 2014-06-30
      • 1970-01-01
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      相关资源
      最近更新 更多