每秒调用一个方法android

时间:2015-11-10 18:32:23

标签: java android

有没有办法每隔几秒调用一次方法,比如unity3d中的更新? 我试过这个:但它在处理程序

上给了我很多错误
Handler h = new Handler();
int delay = 100; //milliseconds

h.postDelayed(new Runnable(){
  public void run(){
     //do something
     h.postDelayed(this, delay);
  }
}, delay);

1 个答案:

答案 0 :(得分:1)

您可以使用Java Threads

public static void main(String[] args)
{
    Runnable myRunnable = new Runnable(){
         public void run(){
            while(true)
            {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Thread thread = new Thread(new Runnable(){
                    public void run(){
                        System.out.println("Run...");
                    }
                });
                thread.start();
            }
         }
    };

    Thread thread = new Thread(myRunnable);
    thread.start();
}