zekikos
zekikos

Reputation: 3

Android Canvas Using Too Much CPU

I'm making simple 2D game with canvas in android. I think it's enough for my game. But locking and unlocking canvas operations using around %40-%50 CPU. Is this normal? or What should i do? There is my game loop code:

while(GVars.isGameRunning){
        c=holder.lockCanvas();
        p.setColor(Color.argb(255, 229, 43, 68));
        c.drawRect(GMethods.createRec(0,0,GVars.size[0], 90),p);
        for (int i = 0; i < GVars.size[0]/110; i++){
            c.drawRoundRect(new RectF(i*100+30,100,i*100+130,100+100),10,10,p);
        }
        p.setColor(Color.argb(255,255,255,255));
        p.setTextSize(50);
        c.drawText("Simple text:", 0,60, p);
        holder.unlockCanvasAndPost(c);
        try{Thread.sleep(GVars.waitTime/*waitTime =30*/);}catch(Exception ex){};
    }

Sorry for my English.

Edit: I tried once again like this.(In main thread) And it's now using %10 of cpu. I think it's what i want. :D Thanks!

   @Override
public void onDraw(Canvas c){
    p.setTextSize(50);
    for (int i = 0; i < GVars.size[0]/110; i++){
        p.setColor(Color.argb(255,183, 33, 53));
        c.drawRoundRect(new RectF(i*100+i*10, 100+5, i*100+100+i*10, 100+100+10),10,10,p);
    }
    p.setColor(Color.argb(255,255,255,255));
    c.drawText("Test:", 0,60, p);
    invalidate();
    try{Thread.sleep(20);}catch (Exception ex){}
}

Upvotes: 0

Views: 228

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83577

The loop in your code blocks the main event thread. Instead, you should use the event mechanism from the Android API. Specifically, you need to override View.onDraw().

Upvotes: 1

Related Questions