2010-09-08 52 views
1

我想创建一个画布上的游戏动画的Android中的绘画和更新循环,但我有麻烦,因为我似乎无法让线程正常工作。它似乎几乎立即崩溃。这是我曾尝试过的:如何实现paint-update循环?

// 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(); 
    } 
} 

此外,当我等待下降更低崩溃更快。

是否有更合适的方法来解决这个问题?

更改为此:

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(); 
} 

}

这导致了同样的错误...:/

+0

你可以发布日志 – Vinay 2010-09-08 15:45:36

+0

我如何获得上述日志? – tylercomp 2010-09-08 15:49:14

+0

如果您使用的是eclipse,请打开ddms或logcat窗口。如果您不使用eclipse,请从命令行运行adb logcat(或Windows上的adb.exe logcat)。 adb位于tools文件夹中。 – 2010-09-08 16:03:18

回答

1

你错过了'循环'。

您不应该在已经启动的线程上手动调用run方法。

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

我实际上不会使用上述两种方法,我会使用Timer或Android等价物。你应该从中得到这个概念。

4

嗯,我注意到的第一件事就是运行调用更新和更新调用run 。这会导致一个没有PUN INTENDED的堆栈溢出。他们互相打电话,直到堆栈填满。然后它应该崩溃。

+0

oh ... man ...好的 – tylercomp 2010-09-08 16:27:32