2012-03-23 74 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; 
}