2014-02-27 91 views
1

我有這段代碼。在我的代碼中,我需要延遲操作啓動(它工作正常),但在操作中我需要檢查InitInProcess()值。如果爲假,則斷開循環,如果爲真,則等待500ms並再次檢查。但結果我得到的檢查靈巧,而不是每隔500毫秒。延遲循環並暫停它

Handler myHandler = new Handler(); 
     myHandler.postDelayed(new Runnable() { 

      @Override 
      public void run() { 

       int test = 0; 
       while (test!=20) 
       { 
        if (InitInProcess()) 
         break; 

        try { 
         Thread.sleep(500); 
        } catch (InterruptedException e) { 

         e.printStackTrace(); 
        } 

        Log.d("MyApp", ""+test); 


        test++; 
       } 

      } 
     }, 3000); 

日誌(看時間):

02-27 12:48:41.707: D/MyApp(10082): 0 
    02-27 12:48:42.212: D/MyApp(10082): 1 
    02-27 12:48:42.712: D/MyApp(10082): 2 
    02-27 12:48:43.267: D/MyApp(10082): 3 
    02-27 12:48:43.767: D/MyApp(10082): 4 
    02-27 12:48:44.272: D/MyApp(10082): 5 
    02-27 12:48:44.772: D/MyApp(10082): 6 
    02-27 12:48:45.277: D/MyApp(10082): 7 
    02-27 12:48:45.777: D/MyApp(10082): 8 
    02-27 12:48:46.277: D/MyApp(10082): 9 
    02-27 12:48:46.777: D/MyApp(10082): 10 
    02-27 12:48:47.277: D/MyApp(10082): 11 
    02-27 12:48:47.772: D/MyApp(10082): 12 
    02-27 12:48:48.277: D/MyApp(10082): 13 
    02-27 12:48:48.777: D/MyApp(10082): 14 
    02-27 12:48:49.277: D/MyApp(10082): 15 
    02-27 12:48:49.777: D/MyApp(10082): 16 
    02-27 12:48:50.277: D/MyApp(10082): 17 
    02-27 12:48:50.782: D/MyApp(10082): 18 
    02-27 12:48:51.277: D/MyApp(10082): 19 
+2

我錯了???這些是500毫秒的步驟。 –

+0

500ms是0.5秒,全部在12:48 – Dim

+0

哦....抱歉,我因爲疲倦而犯了愚蠢的錯誤,這是500ms,我看了一下分鐘。新人的東西! – Dim

回答

1
private static final long RETRY_DELAY = 500; 
private static final int RETRY_COUNT = 10; 
private Handler myHandler = new Handler() { 
     @Override 
     public void handleMessage(android.os.Message msg) { 
      if (!InitInProcess() && msg.what>0) { 
       myHandler.sendEmptyMessageDelayed(msg.what-1, RETRY_DELAY); 
      } 
     } 
    }; 

    myHandler.sendEmptyMessageDelayed(RETRY_COUNT, RETRY_DELAY); 
2
int test = 0; 
while (test!=20){ 
     if (InitInProcess()) 
      break; 

try { 
    myHandler.postDelayed(new Runnable() { 
        test++; 
Log.d("MyApp", ""+test); 
     },500); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

}

+0

延時500ms在哪裏? – Dim

+0

使用500個3000的地方 –