2014-02-27 55 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的地方 –