Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracking Fragment Lifecycle like Application.ActivityLifecycleCallbacks

Everyone knows that in Android we can track Activities via Application.ActivityLifecycleCallbacks to obtain fires from system, when Activity created, stopped, destroyed, etc.

I found only one question on stackoverflow related to this theme.
Hooking into fragment's lifecycle like Application.ActivityLifecycleCallbacks

Unfortunately provided solution works only on post 25.2.0 Android.
I'm looking for soultion for pre 25.2.0. Maybe it could possible via some workarounds, reflection maybe?

like image 672
Sergey Shustikov Avatar asked Sep 12 '25 14:09

Sergey Shustikov


1 Answers

I'm looking for soultion for pre 25.2.0

FragmentManager.FragmentLifecycleCallbacks was available from 25.1.0. The only change, that was introduced in 25.2.0 concerning this API is, that it became static, and before that it was just a public inner class. Which means in order to use you have to access it via its enclosing instance, which in this case is FragmentManager:

final FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.registerFragmentLifecycleCallbacks(fragmentManager.new FragmentLifecycleCallbacks() {
            @Override
            public void onFragmentPreAttached(FragmentManager fm, Fragment f, Context context) {
                super.onFragmentPreAttached(fm, f, context);
            }
            ...
            // all other callbacks
        }, true);

As mentioned in Eugen Pechanec's comment, default framework fragments (i.e. android.app.Fragment, not from support packages) will receive these changes in Android-O release.

like image 125
azizbekian Avatar answered Sep 14 '25 05:09

azizbekian