2013-02-26 61 views
1

在for循環中,有一個調用handler.post()的方法。在for循環中存在一條記錄語句,其中打印日誌消息16次(表示循環執行了16次)。同樣,run()中還有一條日誌消息,但不幸的是,應用程序打印此日誌消息300次(大約),理想情況下應該只打印16次。有人能指導我瞭解錯誤嗎?Android中處理程序的代碼

代碼片段是:

 do 
    { 
     final Handler handler = new Handler(); 
     System.out.println("KKKKKKKKKKKKKKKKKKKKKKKKKKKK"); 
     handler.post(new Runnable() { 
     @Override public void run() { 
      System.out.println("IIIIIIIIIIIIIIIIIIIIIIIIII"); 

       // Post again 16ms later. 
       boolean booleanHandler= handler.postDelayed(this, 32); 
       System.out.println("******************************"+booleanHandler); 
      } }); 
    } 
while(16 times) 

編輯:如果狀態拆下

回答

0

這樣做:

//declare like this 
private Handler handler = new Handler(); 

// call in oncreate() 
handler.postDelayed(runnable, 30000); //30sec 

//inside this function which u have to run 
private Runnable runnable = new Runnable() { 
    public void run() { 


     handler.postDelayed(this, 30000); 
    } 
}; 
+0

我可以在循環中執行處理程序嗎? – 2013-02-26 09:44:14

+0

亞......你可以在循環中使用 – 2013-02-26 09:48:18

+0

上面代碼中的問題是什麼? – 2013-02-26 09:51:08

0

這是處理程序的無限通話,因爲的T值似乎並不T爲您處理

0

內部改變問題在變量t中。如果(t> = 0 & & t < = 1.0)爲真,那麼你的代碼會一次又一次地將自己放入一個處理程序中,直到t被更改爲止。所以,如果你只需要16次執行,那麼你不應該在你的Runnable中調用handler.post(),或者在執行之前改變它。

+0

對不起,這裏的t值是變化的,但它沒有反映我們的條件 – 2013-02-26 09:56:50

+0

還有一個猜測:如果你從另一個線程變化率T,那麼你應該考慮使用「揮發性」鍵-word - 因此,您可以避免由VM更新t值的延遲。 – tundundun 2013-02-26 10:43:06