tags:

views:

32

answers:

2

I want to create a paint and update loop in android for game animation on a canvas but I am having trouble as I can't seem to get the threading to work appropriately. It seems to crash almost immediately. Here is what I have tried:

    // Create the thread supplying it with the runnable object
    Thread thread = new Thread(runnable);

    // Start the thread in oncreate()
    thread.start();


    class runner implements Runnable {
    // This method is called when the thread runs
    long wait = 1000;

    public void run() {

    update();
    }

    public void update()
    {
        try{
          Thread.currentThread();
            //do what you want to do before sleeping
          Thread.sleep(wait);//sleep for 1000 ms
          //do what you want to do after sleeping
        }
        catch(InterruptedException ie){
        //If this thread was interrupted by another thread 
        }

        run();
    }
}

Also when I drop the wait down lower it crashes faster.

Is there a more appropriate way to approach this?

Changed to this:

class runner implements Runnable {
// This method is called when the thread runs
long wait = 10;
boolean blocked = false;

public void run() {

    if(!blocked){
        blocked = true;
        paint();
    }
}


public void paint()
{

    update();
}


public void update()
{
    try{
      Thread.currentThread();
        //do what you want to do before sleeping
      Thread.sleep(wait);//sleep for 1000 ms
      //do what you want to do after sleeping
    }
    catch(InterruptedException ie){
    //If this thread was interrupted by another thread 
    }

    paint();
}

}

This results in the same error... :/

+3  A: 

Well the first thing I notice is that run calls update and update calls run. This is going to cause a NO PUN INTENDED Stack Overflow. They call each other until the stacks fills up. Then it should crash.

Jimmie Clark
oh ... man ... okay
tylercomp
+1  A: 

You are missing your 'loop'.

You should NOT call run manually on an already started thread.

public void run()
{
  while (true)
  {
    // do whatever
    Thread.sleep(wait);
  }
}

I would not actually use the above either, I'd use a Timer or Android equivalent. You should get the concept from this though.

willcodejavaforfood