如何阻止处理程序执行

时间:2014-09-24 14:00:51

标签: android

我创建了一个自定义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);
        }
    });

}

1 个答案:

答案 0 :(得分:0)

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