2016-11-22 47 views
0

我已經看過這裏的問題:Android Runnable runs faster after Resume 但它不能解決我的問題。 我有一個可運行的片段,每5秒更改一次圖像。當我第一次移動到片段時,它是活動中的第一個片段,它很好:圖像每5秒鐘更換一次。 但是,如果我移動到另一個片段並返回,則可運行的運行速度會更快,因此一些圖像每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似乎並不奏效,當用戶移動從這個片段遠仍有調用的可運行。 任何幫助,非常感謝。 謝謝。

回答

2

這可能是因爲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(); 
    } 
} 
+0

謝謝。如果我這樣做了,那我已經嘗試過了,那麼它在計時器被取消並且不能啓動時就會崩潰。 – user3079872

+0

我取消計時器時得到的錯誤是'java.lang.IllegalStateException:計時器被取消' – user3079872

+0

我得到它與您的建議一起工作,然後重置OnResume中的計時器。非常感謝! – user3079872