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似乎并不奏效,当用户移动从这个片段远仍有调用的可运行。 任何帮助,非常感谢。 谢谢。
谢谢。如果我这样做了,那我已经尝试过了,那么它在计时器被取消并且不能启动时就会崩溃。 – user3079872
我取消计时器时得到的错误是'java.lang.IllegalStateException:计时器被取消' – user3079872
我得到它与您的建议一起工作,然后重置OnResume中的计时器。非常感谢! – user3079872