2017-09-02 40 views

回答

0

有兩種方法可以解決您的問題。

  1. 如果您要檢查,並相應地做好每10秒後,你應該使用一個Handler工作的任何條件。

  2. 如果沒有任何條件,並且你只是想在每10秒後運行代碼。那麼TimerTask也是一種方式。我實際上曾與TimerTask類。所以我說這很容易。

創建你class貫徹methods

class myTaskTimer extends TimerTask{ 

     @Override 
     public void run() { 
      Log.e("TAG", "run: "+"timer x"); 
     } 
    } 

,現在在你的代碼創建一個新的Timer對象和initialize它。

Timer t = new Timer(); 

現在,你可以在指定的時間間隔後,安排在裏面你的任務象下面這樣:

t.scheduleAtFixedRate(new myTaskTimer(),10000,10000); 

功能如下解釋:

無效scheduleAtFixedRate(TimerTask的任務, 長延遲, 長週期)

安排指定的任務對於重複的固定利率執行, 在指定的延遲後開始。隨後的執行以大約固定的時間間隔 進行,由指定的時間段分隔。

現在爲handler,下面是代碼,它可以檢查任何條件。代碼取自here尋求幫助。

private int mInterval = 10000; // 10 seconds as you need 
private Handler mHandler; 

@Override 
protected void onCreate(Bundle bundle) { 

    // your code here 

    mHandler = new Handler(); 
    startRepeatingTask(); 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    stopRepeatingTask(); 
} 

Runnable mStatusChecker = new Runnable() { 
    @Override 
    public void run() { 
      try { 
       updateStatus(); //this function can change value of mInterval. 
      } finally { 
       // 100% guarantee that this always happens, even if 
       // your update method throws an exception 
       mHandler.postDelayed(mStatusChecker, mInterval); 
      } 
    } 
}; 

void startRepeatingTask() { 
    mStatusChecker.run(); 
} 

void stopRepeatingTask() { 
    mHandler.removeCallbacks(mStatusChecker); 
} 

我希望它有幫助。

0

根據@pskink評論使用android.os.Handler。

private void callSomeMethodTwice(){ 
    context.myMethod(); //calling 1st time 
    new Handler().postDelayed(new Runnable(){ 
     @Override 
     public void run(){ 
      context.myMethod(); //calling 2nd time after 10 sec 
     } 
    },10000}; 
}