将 activity 传递给 LifecycleObserver

Pass activity to LifecycleObserver

我需要将 activity 传递给 LifecycleObserver class 以执行定位任务:

class LocationObserver(
        private val context: Context,
        private val activity: FragmentActivity) : LifecycleObserver {
    
    private var locationClient: FusedLocationProviderClient? = null
    private val locationListener = OnSuccessListener { location: Location? ->
        if (location != null) {
            val lat = location.latitude
            val long = location.longitude
            ...
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() {
        locationClient = LocationServices.getFusedLocationProviderClient(activity)
        ...
        locationClient?.lastLocation?.addOnSuccessListener(activity, locationListener)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() {
        locationClient = null
    }
}

在片段中创建并使用了 LocationObserver:

public class LocationFragment extends Fragment {
    private LocationObserver locationObserver;
    
    public View onCreateView(@NonNull LayoutInflater inflater,
                       ViewGroup container, Bundle savedInstanceState) {
        ...
        locationObserver = new LocationObserver(this.getContext(), this.getActivity());
        getLifecycle().addObserver(locationObserver);
        
        return root;
    }
    ...
}

问题是:将activity传递给LifecycleObserver-class会导致内存泄漏吗?如果是这样,解决方案是什么?非常感谢任何 answer/comment!

好吧,如果片段位于 Activity 中,您的 Fragment 可能不会有更长的生命周期,因此即使您保留对 [=18] 的引用也不会真正发生泄漏=].

但只要您删除 LocationObserver 中的所有 Activity 引用,您就会感到很安全。