2015-03-25 75 views
0

我有一个函数每隔0.〜2秒执行一次(由于滞后)。但是,我想每5秒钟敬酒一杯。我可以知道我能做到吗?吐司每X秒

public void navigation(Coordinate userPosition , Coordinate destination){ 
    if (Math.abs(userPosition.y - destination.y) > 500) { 
    {Toast.makeText(this, "Walk for " + Math.abs(CheckPoint.y - UserPosition.y) + "mm", Toast.LENGTH_SHORT).show(); } 
} 

上面是我当前的代码示例。吐司执行的频率取决于当前的“滞后”。我希望最少每5秒发送一次敬酒。

+0

使用的TimerTask或报警经理 – 2015-03-25 09:10:32

+0

更好地利用处理器 – Apurva 2015-03-25 09:13:18

+0

请考虑接受和回答。对于有同样问题的其他人可能会有用。谢谢。 – margabro 2017-08-17 08:51:25

回答

1

尝试一下本作正好五个第二

int count = 100; //Declare as inatance variable 

    Timer timer = new Timer(); 
    timer.schedule(new TimerTask() { 

     @Override 
     public void run() { 
      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        final Toast toast = Toast.makeText(
          getApplicationContext(), --count + "", 
          Toast.LENGTH_SHORT); 
        toast.show(); 
        Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() { 

         @Override 
         public void run() { 
          toast.cancel(); 
         } 
        }, 5000); 

       } 
      }); 
     } 
    }, 0, 5000); 
0

创建一个线程和循环线程

Thread myThread = null; 

    Runnable runnable = new CountDownRunner(); 
      myThread = new Thread(runnable); 
      myThread.start(); 



    class CountDownRunner implements Runnable 
     { 
      // @Override 
      public void run() 
      { 
       while(!Thread.currentThread().isInterrupted()) 
       { 
       try 
       { 
        navigation(); // do the work here 
        Thread.sleep(2000); // time interval for the counter. it will run every 2 sec 
       } 
       catch(InterruptedException e) 
       { 
        Thread.currentThread().interrupt(); 
       } 
       catch(Exception e) 
       { 
       } 
      } 
     } 
    } 

    public void navigation(Coordinate userPosition , Coordinate destination){ 
    if (Math.abs(userPosition.y - destination.y) > 500) { 
    {Toast.makeText(this, "Walk for " + Math.abs(CheckPoint.y - UserPosition.y) + "mm", Toast.LENGTH_SHORT).show(); } 
} 
0
与循环 Thread

也许?试试看:

private Thread loopThread = new Thread(new Runnable() { 
    public void run() { 
     while(true){ 
      try { 
       runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        Toast.makeText(this, "Your text!", Toast.LENGTH_SHORT).show(); 
       }); 
       Thread.Sleep(5000); //Wait 5 seconds, then repeat!  
      }catch (Exception e) { 
        return; 
      }catch (InterruptedException i) { 
        return; 
      } 
     } 
    } 
}); 

,无论你想喜欢然后启动Thread

Thread myThread = new Thread(loopThread); 
myThread.start(); 

而且随着停止:

myThread.interrupt(); 

希望它能帮助!

2

你可以这样来做:

final Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      navigation(...); 
      handler.postDelayed(this, 5000); 
     } 
    }, 5000);