2012-03-23 69 views
1

我需要此線程循環緩慢,並在用戶按下buttonStart後,在integerTime的持續時間內暫停。當談到Android時,我是一個業餘愛好者,並且我花了大約12個小時試圖讓這個工作。如果有人能幫助或糾正我的代碼,我將非常感激。乾杯。爲什麼這個線程暫停並循環?

final Button button = (Button) findViewById(R.id.buttonStart);    // Making the button to launch the 
    button.setOnClickListener(new View.OnClickListener() {      // actions below 
     public void onClick(View v) { 

      editTextTarget = (EditText)findViewById(R.id.editTextTarget);  // After user presses 'Start', it will 
      stringTarget = editTextTarget.getText().toString();    // convert the input 'Target' into a string 

      editTextPayload = (EditText)findViewById(R.id.editTextPayload); // After user presses 'Start', it will 
      stringPayload = editTextPayload.getText().toString();    // convert the input 'Payload' into a string and 
      integerPayload = Integer.parseInt(stringPayload);    // then convert the string into an integer 

      editTextTime =(EditText)findViewById(R.id.editTextTime);  // After user presses 'Start', it will 
      stringTime = editTextTime.getText().toString();    // convert the input 'Time' into a string and 
      integerTime = Integer.parseInt(stringTime);     // then convert the string into an integer 

      Thread threadBegin = new Thread() 
      { 
      public void run(){ 
       while (DOSrunning.get()) { 
       try { 
        Thread.sleep(integerTime);    
       } catch (ClientProtocolException e) { 
       } catch (IOException e) { 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       } 
        } 
      ;}; 

      threadBegin.start(); 
+0

整數時間以毫秒爲單位? – 2012-03-23 22:27:58

+0

您的要求不明確... – waqaslam 2012-03-23 22:30:40

回答

1

你的代碼對我來說很好看。您正在創建一個匿名類,它擴展了Thread,覆蓋了run()方法。你當然需要在run()之前有一個@Override,我很困惑爲什麼你需要下面的捕獲,除非你切除了一些內部循環。我也看不到DOSrunning()設置。它看起來像一個AtomicBoolean這是很好的。你確定它被初始化爲true

AtomicBoolean DOSrunning = new AtomicBoolean(true); 

如果它不是那麼問題一定是在intergerTime值不毫秒。 1000的值會睡1秒。

最後,請務必正確處理InterruptedException。像這樣的是更好的模式:

} catch (InterruptedException e) { 
    // reset the interrupted flag 
    Thread.currentThread().interrupt(); 
    e.printStackTrace(); 
    // quit the thread if necessary 
    return; 
}