1

I am making an android game that needs to run a method continiously, kind of like a timer. I need that it is being called every second. How can i make this possible???

Java code:

import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;

public class ExampleView extends SurfaceView implements SurfaceHolder.Callback
{
class ExampleThread extends Thread
{
    private ArrayList<Parachuter> parachuters;
    private Bitmap parachuter;
    private Paint black;

    private boolean running;

    private SurfaceHolder mSurfaceHolder;
    private Context mContext;
    private Handler mHandler;
    private GameScreenActivity mActivity;

    private long frameRate;
    private boolean loading;

    public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler)
    {
        mSurfaceHolder = sHolder;
        mHandler = handler;
        mContext = context;
        mActivity = (GameScreenActivity) context;

        parachuters = new ArrayList<Parachuter>();
        parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman);
        black = new Paint();
        black.setStyle(Paint.Style.FILL);
        black.setColor(Color.WHITE);

        running = true;

        // This equates to 26 frames per second.
        frameRate = (long) (1000 / 26);
        loading = true;
    }

    @Override
    public void run()
    {
        while (running)
        {
            Canvas c = null;
            try
            {
                c = mSurfaceHolder.lockCanvas();

                synchronized (mSurfaceHolder)
                {
                    long start = System.currentTimeMillis();
                    doDraw(c);
                    long diff = System.currentTimeMillis() - start;

                    if (diff < frameRate)
                        Thread.sleep(frameRate - diff);
                }
            } catch (InterruptedException e)
            {
            }
            finally
            {
                if (c != null)
                {
                    mSurfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }
    }

    protected void doDraw(Canvas canvas)
    {
        canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black);

        //Draw
        for (int i = 0; i < parachuters.size(); i++)
        {
            canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null);
            parachuters.get(i).tick();
        }

        //Remove
        for (int i = 0; i < parachuters.size(); i++)
        {
            if (parachuters.get(i).getY() > canvas.getHeight())
                parachuters.remove(i);
        }
    }

    public boolean onTouchEvent(MotionEvent event)
    {
        if (event.getAction() != MotionEvent.ACTION_DOWN)
            return false;

        float x = event.getX();
        float y = event.getY();

        Parachuter p = new Parachuter(x, y);
        parachuters.add(p);
        Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();

        return true;
    }
    public void setRunning(boolean bRun)
    {
        running = bRun;
    }

    public boolean getRunning()
    {
        return running;
    }
}

/** Handle to the application context, used to e.g. fetch Drawables. */
private Context mContext;

/** Pointer to the text view to display "Paused.." etc. */
private TextView mStatusText;

/** The thread that actually draws the animation */
private ExampleThread eThread;

public ExampleView(Context context)
{
    super(context);

    // register our interest in hearing about changes to our surface
    SurfaceHolder holder = getHolder();
    holder.addCallback(this);

    // create thread only; it's started in surfaceCreated()
    eThread = new ExampleThread(holder, context, new Handler()
    {
        @Override
        public void handleMessage(Message m)
        {
           // mStatusText.setVisibility(m.getData().getInt("viz"));
           // mStatusText.setText(m.getData().getString("text"));
        }
    });

    setFocusable(true);
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
    return eThread.onTouchEvent(event);
}

public ExampleThread getThread()
{
    return eThread;
}

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
    // TODO Auto-generated method stub
}

public void surfaceCreated(SurfaceHolder holder)
{
    if (eThread.getState() == Thread.State.TERMINATED)
    {
        eThread = new ExampleThread(getHolder(), getContext(), getHandler());
        eThread.start();
    }
    else
    {
        eThread.start();
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
    boolean retry = true;
    eThread.setRunning(false);

    while (retry)
    {
        try
        {
            eThread.join();
            retry = false;
        }
        catch (InterruptedException e)
        {
        }
    }
}
}

I need to add a function or a socalled "method", a public void or something like that, that should be called every second and should do the exact same code as the MotionEvent event method, the onTouchEvent.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
user1183066
  • 115
  • 2
  • 6
  • 20

2 Answers2

1

Following Rob's commented link, consider (which is not the accepted answer, though) reviewing this from the Android Developer's site, Resources section: http://developer.android.com/resources/articles/timed-ui-updates.html

It describes how to use the android os Handler class to implement a timer, rather than using the Timer and TimerTask classes themselves.

Maximus
  • 8,351
  • 3
  • 29
  • 37
0

This pretty much what you are looking for. How to run a Runnable thread in Android?

It does sth every 1000ms using a thread.

Community
  • 1
  • 1
Calvin
  • 3,302
  • 2
  • 32
  • 41