【问题标题】:how to stop handler from executing如何停止处理程序执行
【发布时间】:2014-09-24 14:00:50
【问题描述】:

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

}

【问题讨论】:

  • 添加更多线程行为,以便您可以观察/停止线程。 stackoverflow.com/questions/5657709/…
  • @RobertRowntree 要使线程正常运行,我需要知道此控件是否可见。这就是我卡住的地方。是否有回调让我知道布局何时进入和消失?
  • 不知道你的具体情况......但是,一般来说,你在线程上的 OP 会解释一些 git , impl 的“记录器”,因为它们都使用开始/停止按钮控制执行实际记录的线程的 UI。你的计时器很相似....github.com/Audioboo/audioboo-android/blob/master/src/fm/…
  • 跟踪 UI 状态属于 MVC 状态管理以及您为此所做的任何事情。我想你可以回调到 Activity 中的接口以跟踪你的 UI 状态?

标签: android


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2021-11-12
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    相关资源
    最近更新 更多