Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android handler removeCallbacks not working

i 'm rotating image with runnable.i want to rotate image for example 4 th time and then pause/stop rotate.i wrote some function

public void rotateImage(final View myView, final int size) {

    runnable = new Runnable() {

        @Override
        public void run() {

            count++;
            myView.setRotation(myView.getRotation() + size);
            if (count ==3) {
                myHandler.removeCallbacks(runnable);
            }

            myHandler.postDelayed(this, 100);
            // 1000 means 1 second duration
        }
    };
    myHandler.postDelayed(runnable, 100); 

}

i can rotate image but i can't stop/pause rotating .removeCallbacks not working at the moment what is a wrong in my code if anyone knows solution please help me

like image 937
viviano Avatar asked Oct 24 '14 10:10

viviano


2 Answers

I had the same logic on my Handler/Runnable. And it was also not stopping.

What I did was: at my Activity's OnDestroy, I called

myHandler.removeCallbacksAndMessages(null);

And it finally stopped.

Hope it helps.

like image 195
Victor Lee Avatar answered Sep 27 '22 18:09

Victor Lee


/**
 * <p>Removes the specified Runnable from the message queue.</p>
 *
 * @param action The Runnable to remove from the message handling queue
 *
 * @return true if this view could ask the Handler to remove the Runnable,
 *         false otherwise. When the returned value is true, the Runnable
 *         may or may not have been actually removed from the message queue
 *         (for instance, if the Runnable was not in the queue already.)
 *
 * @see #post
 * @see #postDelayed
 * @see #postOnAnimation
 * @see #postOnAnimationDelayed
 */
public boolean removeCallbacks(Runnable action)

removeCallbacks() only works when the runnable is pendding in the message queue. The runnable you want to remove is obviously running.

You'd better stop it by yourself. Like:

public void rotateImage(final View myView, final int size) {

runnable = new Runnable() {

    @Override
    public void run() {

        count++;
        myView.setRotation(myView.getRotation() + size);
        if (count ==3) {
            //myHandler.removeCallbacks(runnable);
        } else {
            myHandler.postDelayed(this, 100);
        }
        // 1000 means 1 second duration
    }
};
myHandler.postDelayed(runnable, 100); 

}

like image 36
Ronnie Hwang Avatar answered Sep 27 '22 17:09

Ronnie Hwang