2014-09-24 138 views
0

我创建了一个自定义compound control用于在我的列表视图中显示计时器。其中,我使用一个处理程序每​​1秒更新显示的计时器值。问题是,即使列表项滚动出视图,或者即使我退出应用程序,该处理程序仍会继续执行。我如何阻止这个处理程序执行?我试过handler.removeCallbacks(),但它似乎没有工作。如何停止处理程序执行

public class TimerLayout extends LinearLayout { 

    private static final String LOG_TAG = "TimerLayout"; 
    Date startTime; 
    TextView tv_timer; 
    Button btn_cancelTimer; 
    Runnable updateTimerThread; 
    Handler handler; 

    public TimerLayout(Context context, AttributeSet attrs) { 
     super(context,attrs); 
     setOrientation(LinearLayout.VERTICAL); 

     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     inflater.inflate(R.layout.timer, this, true); 
     tv_timer = (TextView) getChildAt(0); 
     btn_cancelTimer = (Button) ((ViewGroup) getChildAt(1)).getChildAt(1); 
     handler = new Handler(); 

     updateTimerThread = new Runnable(){ 

      @Override 
      public void run() { 

       //calculate total time 
       long timeInMilliSeconds = (new Date().getTime()) - startTime.getTime(); 
       int secs = (int) (timeInMilliSeconds/1000) % 60 ; 
       int mins = (int) ((timeInMilliSeconds/(1000*60)) % 60); 
       int hours = (int) ((timeInMilliSeconds/(1000*60*60)) % 24); 
       tv_timer.setText(String.format("%02d", hours) 
         + ":" + String.format("%02d", mins) 
         + ":" + String.format("%02d", secs) 
         ); 

       handler.postDelayed(this, 1000); 
      } 

     }; 

    } 

    public void start(Date startTime) { 

     if (startTime != null) { 
      this.startTime = startTime; 
      handler.postDelayed(updateTimerThread, 0); 
     } 

    } 

    btn_cancelTimer.setOnClickListener(new OnClickListener(){ 

     @Override 
     public void onClick(View view){ 
      handler.removeCallbacks(updateTimerThread); 
     } 
    }); 

} 
+0

添加更多线程行为,以便您可以观察/停止线程。 http://stackoverflow.com/questions/5657709/what-happens-to-java-thread-after-a-join-call-with-timeout – 2014-09-24 14:21:42

+0

@RobertRowntree为了使线程的行为,我需要知道这个控制是可见与否。这就是我被卡住的地方。是否有回调让我知道布局什么时候进入和退出视图? – faizal 2014-09-24 14:39:23

+0

不知道你的具体情况......但是,一般来说,你在线程上的OP会解释一些在'录音机'的任何git,impl中,因为他们都使用UI上的开始/停止按钮来控制线程记录。你的计时器是类似的.... https://github.com/Audioboo/audioboo-android/blob/master/src/fm/audioboo/application/BooRecorder.java – 2014-09-24 15:19:47

回答

0

改为使用框架的计时器并停止它在活动/片段的onPause()中。见here。天文钟已经有它自己的处理程序,并公开方法来启动和停止它。