I have a Document fragment
which is inside viewpager
and i use same Document fragment's instance in another part of application. My problem is that, in fragment i am registering a broadcast receiver, normally i am unregistering it onPause
method in fragment. But fragments onPause
method is not called when i switch another. So next fragment of viewpager
i use new instance of Document fragment and i am creating new instance of receiver also. But onReceive
method receiver calls viewpager's document fragment
method. So when look at logcat i can see that i can not unregister receiver. How can i unregister receiver, can i get list of registered receviers?
Try to register and unregister Broadcast Receivers in the ViewPager's OnPageChangeListener
. This listener contains 3 methods namely onPageScrollStateChanged(int state)
, onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
and onPageSelected(int position)
.
Use onPageScrolledStateChanged()
method. It uses 3 states for monitoring the Fragments inside the ViewPager. Use SCROLL_STATE_DRAGGING
for unregistering your BroadcastReceiver and SCROLL_STATE_SETTLING
for registering your BroadcastReceiver.
也许您可以在片段中使用setUserVisibleHint()方法...或另一个想法,在视图分页器上注册OnPageChangeListener,然后从此侦听器中手动调用方法以注销接收者...
Thank you all for your answers, as you said i implemented OnPageChangeListener
and created a logic, it is working fine now. Thank you all again, i am posting the code:
@Override
public void onPageSelected(int position) {
Fragment currentFragment = adapterViewPager.getRegisteredFragment(position);
if(currentFragment.getClass()==Document.class){
Log.i (AppConfig.TAG,"Current Fragment is Document");
Document document = (Document)currentFragment;
document.registerDownloadService();
}
if(lastFragment!=null && lastFragment.getClass()==Document.class){
Log.i (AppConfig.TAG,"Previous Fragment is Document");
Document document = (Document)lastFragment;
document.unregisterDownloadService();
}
lastFragment = currentFragment;
}
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.