I have a FragmentActivity, some fragments and a service that is running in background. It is possible to check from the service if a specific fragment is visible?
In ViewPager2 and ViewPager from version androidx. fragment:fragment:1.1. 0 you can just use onPause and onResume callbacks to determine which fragment is currently visible for the user. onResume callback is called when fragment became visible and onPause when it stops to be visible.
To retrieve the NavController for a fragment, activity, or view, use one of the following methods: Kotlin: Fragment. findNavController()
This method allows you to retrieve the instance of a previously added fragment with the given tag regardless of the container it was added to.
Since all fragments are destroyed if the activity is destroyed, a simple answer could be calling getActivity(). isDestroyed() returning true if the activity is destroyed, therefore the fragment is destroyed.
check if(YourFragment.this.isVisible())
public boolean isFragmentUIActive() { return isAdded() && !isDetached() && !isRemoving(); }
Does the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With