【发布时间】:2017-07-06 19:59:22
【问题描述】:
我有一个使用位置管理器 (android.location.LocationManager) 的片段。 mLocationManager 和 mLocationListener (android.location.LocationListener) 是片段的私有变量。
在 onResume() 中
mLocationListener = new ABCLocationListener();
mLocationManager = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000L, 0F, mLocationListener);
在 onPause() 中
mLocationManager.removeUpdates(mLocationListener);
mLocationListener = null;
我的 ABCLocationListener 泄漏了。
logcat D/LeakCanary: | mListener = com.xyz.android.presentation.MyFragment$ABCLocationListener@863187568 (0x33733270)
我检查了什么?
1) 正在创建的 ABCLocationListener 对象的哈希值不同于 0x33733270。
2) onResume 和 onPause 方法都只被调用一次。在调用 removeUpdates 和 requestLocationUpdates 之前,这两个方法中监听器的哈希值是相同的
【问题讨论】:
-
该片段的父级类型 - 它是 ViewPager 还是 Tabs?还要避免每次都从 onResume() 创建新对象。只需创建一次,然后注册和注销。
标签: android android-fragments memory-leaks location