Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do something repeatedly while a button is pressed?

I'm developing a TV-Remote Simulator app in Android using a specific middleware (not of importance).

In the case of Volume Buttons (Volume+ and Volume-), what I'm trying to do is to send the "Volume Up" signal repeatedly while its button is pressed.

That's what I tried at last (code for one of the buttons, the other must be identical except for the names):

  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;
        }
    });
    

I've also tried with simple threads as in Increment-Decrement counter while button is pressed but neither worked. The application works finely for the rest of the buttons (channels, etc.), but volume changing is completely ignored.

like image 391
Truncarlos Avatar asked Nov 27 '12 11:11

Truncarlos


2 Answers

You forgot to add a break; at the end of the MotionEvent.ACTION_DOWN: case. That means the line pressedUp = false; gets executed even on that action. The correct thing to do would be:

@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;
}
like image 162
Tas Morf Avatar answered Oct 05 '22 11:10

Tas Morf


Have you considered

  • Starting your repititive task on the onKeyDown event
  • Stopping the task on the onKeyUp event ?
like image 43
Vinay W Avatar answered Oct 05 '22 09:10

Vinay W