androidtimerondrawflashingandroid-view-invalidate

Timer not working in Android when calling invalidate()


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!


Solution

  • 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.