我需要将活动传递给 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 类会导致内存泄漏吗?如果是这样,可能的解决方案是什么?非常感谢您的任何回答/评论!