Search code examples
androidrunnable

Android: onLongClickListener while - Falls into infinite loop and hangs app


I am making audio player and I got all other parts working except for fast forward and rewind buttons.

I didn't know how to make it so when I hold down fast forward or rewind button - it would increment progress and when let go it would stop and start playing music from that part.

I wrote this:

   forwardButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            while(v.isPressed()){
            currentProgress.setProgress((currentProgress.getProgress()+1));
            }
            return false;
        }
    });

but when I hold down fast forward, the app falls into infinite loop basically and hangs causing android to give me option to Wait or Terminate.

I think I need to implement Runnable on it and do it via that to avoid hanging but I am not sure how to do it.

Help?

Variables:

forwardButton = Fast Forward button.
currentProgress = seekbar for music.
mPlayer = music player. 

Solution

  • Dont do it like that. Instead, use a handler and inside the runnable include your while bucle which will be posting setProgress() on your main thread. Everytime you post a forward order, make a delay of X seconds, then check if button keeps clicked, if so, repost runnable.