събота, март 12, 2011

Android simple game loop 1 - j2me style

A simple (almost empty) game loop in Android, which is done the same way, as it is commonly done in J2ME game programming. View (Canvas) implements runnable and starts a thread itself. The interesting thing here is, that I cannot call invalidate() method of the VIEW from another thread (the run() method, when moving objects is done) and instead I must call postInvalidate(), which is sending a message to the UI thread message queue. This means that the drawing is not performed immediately, but when the UI thread handles the message.

Activity class:
package com.test.drawcanvas;

import android.app.Activity;
import android.os.Bundle;

public class DrawCanvas extends Activity
{
    private static DrawView mDrawView = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);        
        mDrawView = new DrawView(this);
        setContentView(mDrawView);
    }
    
    @Override
    public void onResume()
    {
        super.onResume();
        mDrawView.start();
    }

    @Override
    public void onPause()
    {
        super.onPause();
        mDrawView.stop();
    }
}
View class:
package com.test.drawcanvas;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.View;

public class DrawView extends View implements Runnable
{
    public boolean isRunning = false;
    private Context mContext = null;    
    private Thread drawThread = null;   
    private Drawable mIcon = null;
    private int mIconX = 0;
    private int mIconY = 0;
    
    public DrawView(Context context)
    {
        super(context);
        mContext = context;
        mIcon = context.getResources().getDrawable(R.drawable.icon);
    }
    
    
    @Override
    protected void onDraw(Canvas canvas)
    {
        mIcon.setBounds(mIconX, m.IconY, mIconX+48, m.IconY+48);
        mIcon.draw(canvas);         
    }
    
    
    public void start()
    {
        isRunning = true;
        if(drawThread == null)
            drawThread = new Thread(this);
        drawThread.start();
    }
    
        
    public void stop()
    {
        isRunning = false;
        drawThread = null;
    }
    
    
    private void update()
    {
        mIconX++;
        mIconY++;
    }

    
    public void run()
    {
        while(isRunning)
        {
            try
            {
                update();
                postInvalidate();
                drawThread.sleep(20);
            }
            catch(InterruptedException ie) {}
        }
    }
}

1 коментар:

Анонимен каза...

Thanks
very useful
for beginners as me self , delete 2 dots in line
mIcon.setBounds(mIconX, mIconY, mIconX+48, mIconY+48);

and must to have icon.png