Resume 后 Runnable in Fragment 运行得更快

Runnable in Fragment runs faster after Resume

我已经看过这里的问题了:Android Runnable runs faster after Resume 但它不能解决我的问题。 我在片段中有一个可运行的,每 5 秒更改一次图像。当我第一次移动到片段时,它是 activity 中的第一个片段,没问题:图像每 5 秒更改一次。 但是,如果我移动到另一个片段并返回,runnable 运行得更快,所以一些图像每 2 秒更改一次。 我已经尝试了所有我能找到的关于该主题的问题,但我仍然无法正确地做到这一点,因此非常感谢您的帮助。 这是我的代码:

public class Home_Fragment extends Fragment implements RadioGroup.OnCheckedChangeListener {

  Runnable wowUpdateResults;
  Handler wowHandler = new Handler();
  int wowdelay =0 ;
  int wowperiod = 5000;
  Timer wowtimer = new Timer();

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.wow_layout, container, false);
    ....
    wowUpdateResults = new Runnable() {
        public void run() {
            WowAnimateandSlideShow();
        }
    };

    wowtimer.scheduleAtFixedRate(new TimerTask() {
             public void run() {
                 System.out.println("I am on scheduled at fixed rate");
                 wowHandler.post(wowUpdateResults);
             }
         }, wowdelay, wowperiod);
    return view;
}// end of onCreateView

private void WowAnimateandSlideShow() {

  ... //code to get the right image to be shown
  Animation rotateimage2 = AnimationUtils.loadAnimation(getActivity().getBaseContext(), R.anim.fade_in);
  wowprayer.startAnimation(rotateimage2);
}

public void onPause(){
    super.onPause();

  if (wowHandler != null){
        System.out.println("I am on the onPause, removing calls "+wowHandler);
        wowHandler.removeCallbacksAndMessages(wowUpdateResults);
    }
}

 public void onResume(){
    super.onResume();
    wowHandler.postDelayed(wowUpdateResults, 5000); // from the above mentioned question
 }

此外,removeCallbacksAndMessages 似乎不起作用,当用户离开此片段时,仍然会调用 runnable。 任何帮助深表感谢。 谢谢。

可能是因为 Timer 没有停止。在你的onPost方法中取消Timer

public void onPause(){ 
    super.onPause(); 

  if (wowHandler != null){ 
        System.out.println("I am on the onPause, removing calls "+wowHandler);
        wowHandler.removeCallbacksAndMessages(wowUpdateResults);
    } 

  if(wowTimer != null){
     wowTimer.cancel();
  }
}