Skip to content Skip to sidebar Skip to footer

Achieving Accurate Timing In Android

I want to display 60 different colors in 1 second in android. How I can do this that the duration of display(16ms) of all colors is same during 1 second?

Solution 1:

What you need can be achieved in a custom View where you call invalidate() on each onDraw() invocation:

intframesToRedraw=0;


publicvoidstartAnimation(int frames){
     framesToRedraw = frames;
     this.invalidate();
}


/**
 * onDraw override.
 * If animation is "on", view is invalidated after each redraw
 * to make android redraw it on the next frame
 */@OverridepublicvoidonDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (framesToRedraw > 0) {
         // generate new color randomlyfloat[] hsvColor = {0, 1, 1};
         hsvColor[0] = random.nextFloat() * 360f;
         this.setBackgroundColor(Color.HSVToColor(hsvColor));
         framesToRedraw--;
         this.invalidate();  // force the view to be redrawn on each frame
    } 
}

Solution 2:

you already have the math, so try the easy style

//assume im in a different Threadfor(int i=0; i < 17; i++){
    Thread.sleep(16); // add try catchColorc= Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); }

pretty simple

Solution 3:

You can use the Handler class to manage delayed executions. Here you have an example on how to use it to generate a timer every n millis.

finalHandlerhandler=newHandler();
handler.postDelayed(newRunnable(){
    privatestaticfinallongINTERVAL=16L;
    privatelongtime=0;

    @Overridepublicvoidrun(){
        time += INTERVAL;
        if(time <= 1000){
            handler.postDelayed(this, INTERVAL); //Make sure you are calling it after 16 millis
        }
        // Change your color here
        changeColor();
    }
}, INTERVAL);

Post a Comment for "Achieving Accurate Timing In Android"