2016-10-04 85 views
0

我知道如何使用handler和runnable來定期調用一個方法。但是現在我想定期調用多個方法。下面是我的一個類代碼:如何使用處理程序定期調用多個方法?

private Handler handler = new Handler(); 
private Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      for(int index = 0; index < count; index++) { 
        //Do something based on the index value 
      } 
      handler.postDelayed(runnable, 500); 
     } 
    }; 

某處在我的代碼將下面的代碼開始執行:

handler.postDelayed(runnable, 0); 

。因此,對應於指數0第一種方法會被調用首先是其他方法。然後會有500毫秒的延遲來重複相同的操作。

但我還希望在方法調用之間有500毫秒的延遲。我的意思是什麼時候執行for循環。我怎樣才能使用一個處理程序和可運行?如何在方法調用之間產生500毫秒的延遲?

回答

1

我將更新的index跨越Handler調用自己的價值,它就像for循環比較,以你count可變

private Handler handler = new Handler(); 
private Runnable runnable = new Runnable() { 
    private int index = 0; 

    @Override 
    public void run() { 
     //Do something based on the index value 
     index++; 
     if (index < count) { 
      handler.postDelayed(runnable, 500); 
     } else { 
      count = 0; 
     } 
    } 
} 

此外,在一開始你並不需要調用postDelayed()零延遲,您可以直接撥打post()

+0

非常歡迎:) –

相關問題