I need to pass activity to a LifecycleObserver class for a location task:
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
}
}
The LocationObserver is created and used in the fragment:
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;
}
...
}
The question is: will pass activity to LifecycleObserver-class cause a memory leak? If so, what could be the solution? Thank you so much for any answer/comment!