2017-08-09 241 views
0

首先,如果我的標題沒有很好地描述我的問題,但我找不到更好的問題。處理程序不能正常工作

有一個簡單的秒錶應用程序,它有三個按鈕開始,停止,重置和顯示時間的文本視圖。應用程序只有一個這樣的活動:

public class StopwatchActivity extends AppCompatActivity { 

private int mNumberOfSeconds = 0; 
private boolean mRunning = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_stopwatch); 
    //if if uncomment this runner method and delete the runner inside onClickStart everything will work find 
    //runner() 

} 

public void onClickStart(View view){ 
    mRunning = true; 
    runner(); 
} 

public void onClickStop(View view){ 
    mRunning = false; 
} 

public void onClickReset(View view){ 
    mRunning = false; 
    mNumberOfSeconds = 0; 

} 

public void runner(){ 
    final TextView timeView = (TextView) findViewById(R.id.time_view); 
    final Handler handler = new Handler(); 
    handler.post(new Runnable() { 
     @Override 
     public void run() { 
      int hours = mNumberOfSeconds/3600; 
      int minutes = (mNumberOfSeconds%3600)/60; 
      int second = mNumberOfSeconds%60; 
      String time = String.format("%d:%02d:%02d" , hours , minutes , second); 
      timeView.setText(time); 
      if (mRunning){ 
       mNumberOfSeconds++; 
      } 
      handler.postDelayed(this , 1000); 
     } 
    }); 

} 
} 

我的問題是,當我評論亞軍()在onClickStart方法,並把它在onCreate方法一切正常。但是當我更改上面的代碼時,代碼仍在運行,但是在按停止按鈕之後,再次按下啓動按鈕,第二個代碼將以非常快的速度增加4或5。 任何人都可以解釋我有什麼區別這兩種模式?

+0

你殺得了亞軍,所以當你重新啓動定時器,將創建一個季軍。當你只測試mRunning的價值時,第一名選手和第二名選手都會重新開始計時。 – Nick

+0

@Nick爲什麼當我把runner()放在onCreate代碼裏面的時候會發現。我認爲這是相同的場景 –

+0

因爲onCreate只執行一次,所以你只能啓動跑步者的一個實例。 – Nick

回答

1

聲明你處理全球

public void runner(){ 
    timeView = (TextView) findViewById(R.id.time_view); 
    handler = new Handler(); 
    runnable = new Runnable() { 
     @Override 
     public void run() { 
      int hours = mNumberOfSeconds/3600; 
      int minutes = (mNumberOfSeconds%3600)/60; 
      int second = mNumberOfSeconds%60; 
      String time = String.format("%d:%02d:%02d" , hours , minutes , second); 
      timeView.setText(time); 
      if (mRunning){ 
       mNumberOfSeconds++; 
      } 
      handler.postDelayed(this , 1000); 
     } 
    } 
    handler.post(runnable); 

} 

按鈕功能

public void onClickStart(View view){ 
    if(handler != null) { 
     //restart the handler to avoid duplicate runnable 
     handler.removeCallbacks(runnable);//or this handler.removeCallbacksAndMessages(null); 
    } 
    mRunning = true; 
    runner(); 
} 

public void onClickStop(View view){ 
    mRunning = false; 
    handler.removeCallbacks(runnable); // this will stop the handler from working 
} 
+0

當我想運行此代碼,並在應用程序開始後。在按下開始按鈕後,空指針異常將拋出 –

+0

嘗試在空對象引用 –

+0

上調用虛擬方法'void android.os.Handler.removeCallbacks(java.lang.Runnable)'我修復了它。只是在聲明它時實例化Handler。謝謝 –