即使调用removeCallbacks(runnable)也无法停止处理程序

时间:2020-03-22 03:57:23

标签: android

我一直试图在onPause()中停止处理程序。尽管调用了removeCallbacks(timeRunnable)或removeCallbacksAndMessages(timeRunnable),该处理程序仍未停止。我在这里看到了很多答案。但是没有任何效果。我可能在这里错过了一些东西。

代码:

public Runnable timeRunnable = new Runnable() {
    @Override
    public void run() {
        Log.d("Here is my task");
        timeHandler.postDelayed(timeRunnable, 5000);
    }
};

public void startTimeHandler() {
    timeHandler.post(timeRunnable);
}

public void stopTimeHandler() {
    timeHandler.removeCallbacks(timeRunnable);
}

@Override
protected void onPause() {
    super.onPause();
    stopTimeHandler();
}

1 个答案:

答案 0 :(得分:1)

我正在使用下面的代码片段每10秒运行一个线程,并根据从Server收到的值更新UI,并在onPause上停止线程。

在您的课程中声明以下变量:

public class ActivityPortfolio extends AppCompatActivity {
  Handler handler = new Handler();
  Runnable runnable;
  int delay = 10*1000;
 //---------

在您的onResume中:

@Override
protected void onResume() {

    handler.postDelayed(new Runnable(){
        public void run(){

                doSomething();
                handler.postDelayed(this, delay);
        }
    }, delay);

    super.onResume();
}

onPause():

  @Override
protected void onPause() {
    super.onPause();
    handler.removeCallbacks(runnable); // this alone didnt work as we are calling postDelayed() in background as well.
    handler.removeCallbacksAndMessages(null);//after adding this it stops thread
}