0

我需要将活动传递给 LifecycleObserver 类以执行位置任务:

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;
    }
    ...
}

问题是:将活动传递给 LifecycleObserver 类会导致内存泄漏吗?如果是这样,可能的解决方案是什么?非常感谢您的任何回答/评论!

4

1 回答 1

1

好吧,如果片段存在于其中Activity,那么您的生命周期可能Fragment不会更长,因此即使您保留对活动的引用,也不会真正发生泄漏。

但是,只要您删除您的所有Activity参考资料,您LocationObserver就会感到非常安全。

于 2020-10-12T06:30:25.867 回答