I have a simple graphics application which draws some stuff on the screen. Before, I had no problem when I was calling invalidate() in onDraw() without a check. In my application onDraw() is called many times each second (which I came to know through Logs), but I don’t want to call it many times each second, as I want to update the screen after each second only. So I tried to compare previous and current seconds — if they are the same, I won’t call invalidate(); if the second changes, I will call invalidate(). Here is my code:
protected void onDraw(Canvas canvas) {
// Create date to check current second
Date date = new Date();
canvas.drawColor(Color.WHITE);
drawArcs(canvas, mBigOval, mUseCenters[0], mPaints[0]);
//Get the current second
curSec = date.getSeconds();
//compare if its same as lastSec which is updated in drawArcs() which i called before
do {
Log.d("Graphics","curSec="+curSec+" lastSec="+lastSec);
curSec = date.getSeconds();
} while(curSec == lastSec);
Log.d("Graphics","Calling invalidate() and count="+(++count));
invalidate();
}
With the above code, if my application gets launched at the 30th second then the log shows:
06-25 10:25:52.257: D/Graphics(14711): curSec=30 lastSec=30
The above logs keep on repeating with no change in curSec and lastSec. Why is the second not updating even if I’m updating it every time the loop goes through.
Your
Dateobject was created and set to the current time when you instantiated it with:Every time you call
date.getSeconds(), you’re just getting the seconds on that sameDateobject, whose time hasn’t changed.That said, your real issue is that you’re calling
invalidate()fromonDraw(), forcing another call toonDraw()(which forces another…). You don’t need to do that;onDraw()is already called whenever the View becomes invalid. If you’re trying to animate (at 1 fps?) you can use a Handler withpostDelayed()or a SurfaceView and another thread.