Timer not working in Android when calling invalidate()

1k Views Asked by At

I want to create a flashing effect by drawing a path with color grey, white (matching to the background), and then grey again. I want to flash 3 times, showing gray for 1 sec, white for 1 sec gray again for 1 sec, etc.

When I created a Handler for postDelayed(), the program skipped over the run() and did not execute it in the timing set, and no flashing occurred:

final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                invalidate(); //calls onDraw()
                Log.d(TAG, "Flashing now now");
            }
        }, 1000);

How would I implement such a flashing functionality with a timer and flash it 3 times?

Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

You can try something like this,

int delay = 5000; // delay for 5 sec.

int period = 1000; // repeat every sec.

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

public void run() {

System.out.println("done}

}, delay, period);

Otherwise you have plenty other examples to follow like this Example 1, Example 2, Example 3 etc. Let me know if you still need help.

2
On

This is a working code example of how we flash a globe from blue to red and back again. You can modify the code on the inside to limit how many times and what time delay you want.

protected MyGlobeFlasherHandler handlerFlashGlobe = new MyGlobeFlasherHandler(this);

@Override
protected onCreate(Bundle bundle) { 
       handlerFlashGlobe.sendEmptyMessageDelayed(0, 700);
}

/**
 * private static handler so there are no leaked activities.
 */
protected static class MyGlobeFlasherHandler extends Handler {


        private final WeakReference<HomeBase> activity;

        public MyGlobeFlasherHandler(HomeBase activity) {
            this.activity = new WeakReference<HomeBase>(activity);
        }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        if (activity.get() != null) {
            if (activity.get().shadedGlobe) {
                activity.get().imgData.setImageDrawable(activity.get().getResources().getDrawable(R.drawable.globe_blue));
            } else {
                activity.get().imgData.setImageDrawable(activity.get().getResources().getDrawable(R.drawable.globe_red));
            }

            activity.get().shadedGlobe = !activity.get().shadedGlobe;

            sendEmptyMessageDelayed(0, 700);
        }
    }

}