按住按钮时如何重复执行某项任务?

8
我正在使用特定的中间件(不重要)在Android上开发电视遥控模拟器应用程序。
在音量按钮(Volume+和Volume-)的情况下,我想做的是在按住其按钮时重复发送“音量上升”信号。
这是我最后尝试的代码(其中一个按钮的代码,另一个必须完全相同,除了名称)。
  1. Declared a boolean variable

    boolean pressedUp = false;
    
  2. Declared a inner class with the following AsyncTask:

    class SendVolumeUpTask extends AsyncTask<Void, Void, Void> {
    
        @Override
        protected Void doInBackground(Void... arg0) {
            while(pressedUp) {
                SendVolumeUpSignal();
        }
        return null;
    }
    

    }

  3. Add the listener to the button:

    final Button buttonVolumeUp = (Button) findViewById(R.id.volup);
    buttonVolumeUp.setOnTouchListener(new View.OnTouchListener() {
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
    
            case MotionEvent.ACTION_DOWN:
    
                if(pressedUp == false){
                    pressedUp = true;
                    new SendVolumeUpTask().execute();
                }
    
            case MotionEvent.ACTION_UP:
    
                pressedUp = false;
    
        }
            return true;
        }
    });
    

我也尝试了使用简单的线程,例如 增加-减少计数器 但都没有成功。该应用程序在其他按钮(频道等)上运行良好,但是完全忽略了音量更改。

2个回答

3
你忘记在MotionEvent.ACTION_DOWN: case的结尾添加break;。这意味着即使在该操作中,也会执行pressedUp = false;这一行。正确的做法是:
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {

    case MotionEvent.ACTION_DOWN:

        if(pressedUp == false){
            pressedUp = true;
            new SendVolumeUpTask().execute();
        }
    break;
    case MotionEvent.ACTION_UP:

        pressedUp = false;

}
    return true;
}

谢谢,现在信号已经发送。然而,它在短时间内发送了大量的信号。也许应该使用计数器。 - Truncarlos
4
我建议在调用SendVolumeUpSignal()之间设置一个时间间隔。例如,尝试使用以下代码:while(pressedUp){ SendVolumeUpSignal(); Thread.sleep(100);} - Tas Morf

2

你有考虑过

  • onKeyDown 事件上启动你的重复任务吗?
  • onKeyUp 事件上停止任务吗?

1
那些方法不是针对设备的物理按键吗?我是指我的遥控应用程序中的触感按键。 - Truncarlos
是的,名字是这样暗示的...但它们并不是 :-) - Vinay W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接