2015-03-25 74 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);