1 /*
2  * Copyright (C) 2019 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 package leakcanary.internal
17 
18 import android.app.Activity
19 import android.support.v4.app.Fragment
20 import android.support.v4.app.FragmentActivity
21 import android.support.v4.app.FragmentManager
22 import leakcanary.ReachabilityWatcher
23 
24 internal class AndroidSupportFragmentDestroyWatcher(
25   private val reachabilityWatcher: ReachabilityWatcher
26 ) : (Activity) -> Unit {
27 
28   private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
29 
onFragmentViewDestroyednull30     override fun onFragmentViewDestroyed(
31       fm: FragmentManager,
32       fragment: Fragment
33     ) {
34       val view = fragment.view
35       if (view != null) {
36         reachabilityWatcher.expectWeaklyReachable(
37           view, "${fragment::class.java.name} received Fragment#onDestroyView() callback " +
38           "(references to its views should be cleared to prevent leaks)"
39         )
40       }
41     }
42 
onFragmentDestroyednull43     override fun onFragmentDestroyed(
44       fm: FragmentManager,
45       fragment: Fragment
46     ) {
47       reachabilityWatcher.expectWeaklyReachable(
48         fragment, "${fragment::class.java.name} received Fragment#onDestroy() callback"
49       )
50     }
51   }
52 
invokenull53   override fun invoke(activity: Activity) {
54     if (activity is FragmentActivity) {
55       val supportFragmentManager = activity.supportFragmentManager
56       supportFragmentManager.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, true)
57     }
58   }
59 }
60