2017-02-17 55 views
0

我有一個使用位置管理器(android.location.LocationManager)的片段。 mLocationManager和mLocationListener(android.location.LocationListener)是私有變量來片段化。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 = [email protected]87568(0x33733270)

我查過了什麼?
1)創建的ABCLocationListener對象的哈希值與0x33733270不同。
2)onResume和onPause方法只被調用一次。在調用removeUpdates和requestLocationUpdates前兩種方法的監聽器的哈希值是相同

+0

此片段的父類型 - 是ViewPager還是Tabs? 還避免每次從onResume()創建新對象。只需創建一次並註冊並取消註冊。 –

回答

0

檢查this example,但我要說無論是片段的onResume再次被調用,或mLocationListeneronResume實例比你註銷的情況不同在。如果您提供完整片段的源代碼,它可能會有所幫助。爲確保位置偵聽器實例相同,請將該片段本身作爲偵聽器(通過實現LocationListener)並註冊/取消註冊片段(使用this)。

+0

我有日誌。我每次打印onResume時都會打印。我看到onResume和onPause被調用一次。在調用removeUpdates和requestLocationUpdates之前,還需要在兩個方法中調用監聽器 – Amb

+0

您已經自己確定了問題。您正在註銷的監聽器與您正在註冊的監聽器不同。爲了告訴你爲什麼我必須看到代碼,但要解決它,只需使片段本身成爲我已經提到的偵聽器。 –

+0

我的意思是我在onPause和onResume中都有「toString()」編輯監聽器。這兩種方法中的偵聽器都是相同的。此外,我正在記錄無論聽者是誰創建的。我看到偵聽器只創建一次 – Amb

相關問題