提问者:小点点

如何调用按键使用调度KeyEvent一次每次按键在android?


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

@覆盖公共布尔调度KeyEvent(KeyEvent事件){

         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 

  }
        }

共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
}

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