简体   繁体   中英

Android : How to wait until Timer and Timertask finish their work on UI Thread

I have a fragment. In this fragment, I have a Timer that run a timertask periodically. I override onPause so when switch fragment, TimerTask and timer will stop its work.

@Override
        public void onPause() {
            super.onPause();
            timerTask.cancel();
            timer.cancel();
            timer.purge();
        }

And Here is my code for switching fragment :

OrderFragment fragment2 = new OrderFragment();
                    fragment2.setArguments(arguments);
                    getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment2).commit();

But when I switch different fragment, I often receive Null Point Exception because TimerTask cannot access UI Thread anymore (because I have used runOnUIThread )

So, my question is : How to be sure that Timer and TimerTask stop all its work, before I can change fragment.

Thanks :)

Your fragment may not go into the background simply by switching the displayed fragment. It's lifecycle is dependent on the Activity's. I think if you add Log.d("yourFragment", "onPause()"); to the onPause() method you'll find this to be true.

The fragment lifecycle can be found here:

http://developer.android.com/guide/components/fragments.html

Note that it says when your fragment is removed/replaced, but if you're merely displaying another fragment from your activity that doesn't count ;)

It seems like onHiddenChanged(boolean hidden) is what you need. From the Fragment onPause() documentation:

This is generally tied to Activity.onPause of the containing Activity's lifecycle.

So onPause() isn't necessarily called when the Fragment is no longer visible. Move your timer canceling code into onHiddenChanged() .

Put your timer .cancle as a statement just above this as:

timer.cancel();
OrderFragment fragment2 = new OrderFragment();
                fragment2.setArguments(arguments);  
getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container,      
fragment2).commit();


Declare private Timer timer; at class level

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM