4

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?

azizbekian
  • 60,783
  • 13
  • 169
  • 249
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • You can track changes in support library [here](https://developer.android.com/topic/libraries/support-library/revisions.html). Any particular reason not to update? – Eugen Pechanec Apr 11 '17 at 07:49

1 Answers1

4

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.

Community
  • 1
  • 1
azizbekian
  • 60,783
  • 13
  • 169
  • 249
  • 1
    Quick note for completeness, the same feature for *platform* fragments [will be available in Android O](https://developer.android.com/reference/android/app/FragmentManager.FragmentLifecycleCallbacks.html). – Eugen Pechanec Apr 11 '17 at 07:53