8

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.

Community
  • 1
  • 1
Truncarlos
  • 175
  • 2
  • 7

2 Answers2

3

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;
}
Tas Morf
  • 3,065
  • 1
  • 12
  • 8
  • Thanks, now signals are sent. However, it sends a lot of signals for a short pressing period. Perhaps a counter should work. – Truncarlos Nov 27 '12 at 12:43
  • 4
    I would recommend having an interval between calls to SendVolumeUpSignal(); For example try this: `while(pressedUp) { SendVolumeUpSignal(); Thread.sleep(100);}` – Tas Morf Nov 29 '12 at 11:58
2

Have you considered

  • Starting your repititive task on the onKeyDown event
  • Stopping the task on the onKeyUp event ?
Vinay W
  • 9,912
  • 8
  • 41
  • 47