简体   繁体   中英

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?

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 (ie android.app.Fragment , not from support packages) will receive these changes in Android-O release.

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