1 /*
2  * Copyright (C) 2018 Square, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 @file:Suppress("DEPRECATION")
17 
18 package leakcanary.internal
19 
20 import android.annotation.SuppressLint
21 import android.app.Activity
22 import android.app.Fragment
23 import android.app.FragmentManager
24 import leakcanary.ReachabilityWatcher
25 
26 @SuppressLint("NewApi")
27 internal class AndroidOFragmentDestroyWatcher(
28   private val reachabilityWatcher: ReachabilityWatcher
29 ) : (Activity) -> Unit {
30   private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
31 
onFragmentViewDestroyednull32     override fun onFragmentViewDestroyed(
33       fm: FragmentManager,
34       fragment: Fragment
35     ) {
36       val view = fragment.view
37       if (view != null) {
38         reachabilityWatcher.expectWeaklyReachable(
39           view, "${fragment::class.java.name} received Fragment#onDestroyView() callback " +
40           "(references to its views should be cleared to prevent leaks)"
41         )
42       }
43     }
44 
onFragmentDestroyednull45     override fun onFragmentDestroyed(
46       fm: FragmentManager,
47       fragment: Fragment
48     ) {
49       reachabilityWatcher.expectWeaklyReachable(
50         fragment, "${fragment::class.java.name} received Fragment#onDestroy() callback"
51       )
52     }
53   }
54 
invokenull55   override fun invoke(activity: Activity) {
56     val fragmentManager = activity.fragmentManager
57     fragmentManager.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, true)
58   }
59 }
60