1+ import android.app.Application
2+ import android.app.FragmentManager
3+
4+ public class FragmentActivityLifecycleCallbacks (
5+ private val spanTracker : SpanTracker ,
6+ private val spanFactory : SpanFactory ,
7+ private val autoInstrumentationCache : AutoInstrumentationCache ,
8+ ) : Application.ActivityLifecycleCallbacks, FragmentManager.FragmentLifecycleCallbacks() {
9+
10+ private val viewLoadOpts = SpanOptions .makeCurrentContext(false )
11+
12+ override fun onActivityCreated (
13+ activity : Activity ,
14+ savedInstanceState : Bundle ? ,
15+ ) {
16+ if (activity !is FragmentActivity ) return
17+
18+ activity.supportFragmentManager
19+ .registerFragmentLifecycleCallbacks(this , true )
20+ }
21+
22+ override fun onFragmentPreCreated (
23+ fm : FragmentManager ,
24+ f : Fragment ,
25+ savedInstanceState : Bundle ? ,
26+ ) {
27+ if (autoInstrumentationCache.isInstrumentationEnabled(f::class .java)) {
28+ // we start both ViewLoad & ViewLoadPhase/Create at exactly the same timestamp
29+ val timestamp = SystemClock .elapsedRealtimeNanos()
30+ val viewLoad =
31+ spanTracker.associate(f) {
32+ spanFactory.createViewLoadSpan(
33+ ViewType .FRAGMENT ,
34+ viewNameForFragment(f),
35+ viewLoadOpts.startTime(timestamp),
36+ )
37+ }
38+
39+ spanTracker.associate(f, ViewLoadPhase .CREATE ) {
40+ spanFactory.createViewLoadPhaseSpan(
41+ viewNameForFragment(f),
42+ ViewType .FRAGMENT ,
43+ ViewLoadPhase .CREATE ,
44+ SpanOptions .DEFAULTS
45+ .within(viewLoad)
46+ .startTime(timestamp),
47+ )
48+ }
49+ }
50+ }
51+
52+ override fun onFragmentCreated (
53+ fm : FragmentManager ,
54+ f : Fragment ,
55+ savedInstanceState : Bundle ? ,
56+ ) {
57+ if (! f.isAdded) {
58+ // remove & discard the Fragment span
59+ spanTracker.removeAssociation(f, ViewLoadPhase .CREATE )?.discard()
60+ spanTracker.removeAssociation(f)?.discard()
61+ } else {
62+ spanTracker.endSpan(f, ViewLoadPhase .CREATE )
63+ }
64+ }
65+
66+ override fun onFragmentResumed (
67+ fm : FragmentManager ,
68+ f : Fragment ,
69+ ) {
70+ spanTracker.endAllSpans(f)
71+ }
72+
73+ override fun onActivityStarted (activity : Activity ): Unit = Unit
74+
75+ override fun onActivityResumed (activity : Activity ): Unit = Unit
76+
77+ override fun onActivityPaused (activity : Activity ): Unit = Unit
78+
79+ override fun onActivityStopped (activity : Activity ): Unit = Unit
80+
81+ override fun onActivitySaveInstanceState (
82+ activity : Activity ,
83+ outState : Bundle ,
84+ ): Unit = Unit
85+
86+ override fun onActivityDestroyed (activity : Activity ): Unit = Unit
87+ }
0 commit comments