android - 从 onPause 中的 fragment 中删除位置更新时发生内存泄漏

标签 android android-fragments google-play-services fusedlocationproviderapi leakcanary

在我的应用程序的一个 fragment 中,我需要位置更新以确定用户何时靠近一个简短的位置列表,以便用户可以使用相关信息。当我使用

在 onConnected() 回调中创建位置更新请求时
LocationServices.FusedLocationApi.requestLocationUpdates(client, LocationRequest.create(), this);

我还删除了 onPause() 方法中的更新,使用

LocationServices.FusedLocationApi.removeLocationUpdates(client, this);

然而,即使我调用该方法来删除位置更新,我也会收到泄漏金丝雀的警告,每当我离开该 fragment 时,我的 fragment 就会被泄露(所有 fragment 导航都是使用 replace() 事务完成的)。我在我的 fragment 中启动位置请求时做错了什么,还是我没有在 onPause() 中正确清理请求,我们将不胜感激任何帮助。

这是我的 fragment 类的简化模型的代码

public class BlankFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks
    , GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleApiClient client;
private TextView textView;

public BlankFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_blank, container, false);
    textView = (TextView) root.findViewById(R.id.location);
    client = new GoogleApiClient.Builder(getContext())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    return root;
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    startLocationUpdates();
}

private void startLocationUpdates() {
    if (client.isConnected()) {
       LocationServices.FusedLocationApi.requestLocationUpdates(client, LocationRequest.create(), this);

    }
}

private void stopLocationUpdates(){
    LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}



@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
    textView.setText(location.toString());
}

@Override
public void onResume() {
    startLocationUpdates();
    super.onResume();
}

@Override
public void onPause() {
    stopLocationUpdates();
    super.onPause();
}

@Override
public void onStart() {
    client.connect();
    super.onStart();
}

@Override
public void onStop() {
    if (client.isConnected()) {
    client.disconnect();
    }
    super.onStop();
}}

这里还有生成的泄露痕迹

In com.example.testlocation:1.0:1.
* com.example.testlocation.BlankFragment has leaked:
* GC ROOT com.google.android.gms.internal.zzary$zzb.zzaGN
* references com.google.android.gms.internal.zzary$9.zzbkw (anonymous subclass of com.google.android.gms.internal.zzary$zza)
* leaks com.example.testlocation.BlankFragment instance
* Retaining: 7.1 KB.
* Reference Key: 720085d5-af68-42f3-a291-ef959e4c8ffa
* Device: Huawei google Nexus 6P angler
* Android Version: 7.1.2 API: 25 LeakCanary: 1.5 00f37f5
* Durations: watch=5031ms, gc=167ms, heap dump=1418ms, analysis=137993ms
* Details:
* Instance of com.google.android.gms.internal.zzary$zzb
|   static $classOverhead = byte[240]@316980881 (0x12e4be91)
|   zzaGN = com.google.android.gms.internal.zzary$9@316955016 (0x12e45988)
|   mDescriptor = java.lang.String@317419776 (0x12eb7100)
|   mObject = 483616889632
|   mOwner = com.google.android.gms.internal.zzary$zzb@317493408 (0x12ec90a0)
|   shadow$_klass_ = com.google.android.gms.internal.zzary$zzb
|   shadow$_monitor_ = 0
* Instance of com.google.android.gms.internal.zzary$9
|   static $classOverhead = byte[312]@317158785 (0x12e77581)
|   zzbkw = com.example.testlocation.BlankFragment@316908800 (0x12e3a500)
|   zzaxf = com.google.android.gms.common.api.Api@317047488 (0x12e5c2c0)
|   zzazY = com.google.android.gms.common.api.Api$zzf@315109896 (0x12c83208)
|   zzK = true
|   zzaAh = java.lang.Object@315110136 (0x12c832f8)
|   zzaAi = com.google.android.gms.internal.zzaaf$zza@317493376 (0x12ec9080)
|   zzaAj = java.lang.ref.WeakReference@317491784 (0x12ec8a48)
|   zzaAk = java.util.ArrayList@317491760 (0x12ec8a30)
|   zzaAl = null
|   zzaAm = java.util.concurrent.atomic.AtomicReference@317340960 (0x12ea3d20)
|   zzaAn = null
|   zzaAo = false
|   zzaAp = false
|   zzaAq = null
|   zzaAr = null
|   zzaAs = false
|   zzair = com.google.android.gms.common.api.Status@317061968 (0x12e5fb50)
|   zzazt = com.google.android.gms.common.api.Status@317061968 (0x12e5fb50)
|   zztj = java.util.concurrent.CountDownLatch@317340944 (0x12ea3d10)
|   shadow$_klass_ = com.google.android.gms.internal.zzary$9
|   shadow$_monitor_ = -1987877821
* Instance of com.example.testlocation.BlankFragment
|   static serialVersionUID = 8326097604377836997
|   static $change = null
|   static $classOverhead = byte[1168]@315449345 (0x12cd6001)
|   client = com.google.android.gms.internal.zzaat@317202944 (0x12e82200)
|   textView = android.support.v7.widget.AppCompatTextView@317036544 (0x12e59800)
|   mAdded = false
|   mAllowEnterTransitionOverlap = null
|   mAllowReturnTransitionOverlap = null
|   mAnimatingAway = null
|   mArguments = null
|   mBackStackNesting = 0
|   mCalled = true
|   mCheckedForLoaderManager = false
|   mChildFragmentManager = null
|   mChildNonConfig = null
|   mContainer = null
|   mContainerId = 0
|   mDeferStart = false
|   mDetached = false
|   mEnterTransition = null
|   mEnterTransitionCallback = android.app.SharedElementCallback$1@1883261776 (0x70404b50)
|   mExitTransition = null
|   mExitTransitionCallback = android.app.SharedElementCallback$1@1883261776 (0x70404b50)
|   mFragmentId = 0
|   mFragmentManager = null
|   mFromLayout = false
|   mHasMenu = false
|   mHidden = false
|   mHost = null
|   mInLayout = false
|   mIndex = -1
|   mLoaderManager = null
|   mLoadersStarted = false
|   mMenuVisible = true
|   mNextAnim = 0
|   mParentFragment = null
|   mReenterTransition = android.transition.TransitionSet@1883202880 (0x703f6540)
|   mRemoving = false
|   mRestored = false
|   mRetainInstance = false
|   mRetaining = false
|   mReturnTransition = android.transition.TransitionSet@1883202880 (0x703f6540)
|   mSavedFragmentState = null
|   mSavedViewState = android.util.SparseArray@317491880 (0x12ec8aa8)
|   mSharedElementEnterTransition = null
|   mSharedElementReturnTransition = android.transition.TransitionSet@1883202880 (0x703f6540)
|   mState = 0
|   mStateAfterAnimating = 0
|   mTag = null
|   mTarget = null
|   mTargetIndex = -1
|   mTargetRequestCode = 0
|   mUserVisibleHint = true
|   mView = null
|   mWho = null
|   shadow$_klass_ = com.example.testlocation.BlankFragment
|   shadow$_monitor_ = -2047550015
* Excluded Refs:
| Field: android.view.Choreographer$FrameDisplayEventReceiver.mMessageQueue (always)
| Thread:FinalizerWatchdogDaemon (always)
| Thread:main (always)
| Thread:LeakCanary-Heap-Dump (always)
| Class:java.lang.ref.WeakReference (always)
| Class:java.lang.ref.SoftReference (always)
| Class:java.lang.ref.PhantomReference (always)
| Class:java.lang.ref.Finalizer (always)
| Class:java.lang.ref.FinalizerReference (always)

最佳答案

这是一个记录在案且长期存在的问题,即使在调用 removeLocationUpdates 后,Google Maps SDK 也会泄漏内存。您可以阅读更多相关信息 here .

以下解决方法为我删除了泄漏金丝雀通知。

1) 创建一个 WeakLocationListener 类,将位置监听器包装在弱引用中,然后使用此类来处理 onLocationChanged 回调。

public class WeakLocationListener implements LocationListener {

private final WeakReference<LocationListener> locationListenerRef;

public WeakLocationListener(@NonNull LocationListener locationListener) {
    locationListenerRef = new WeakReference<>(locationListener);
}

@Override
public void onLocationChanged(android.location.Location location) {
    if (locationListenerRef.get() == null) {
        return;
    }
    locationListenerRef.get().onLocationChanged(location);
}

2) 创建一个 WeakLocationListener 的实例(使用由您的 fragment 实现的 LocationListener)并在您请求位置更新和移除位置更新时使用它 - 位置将返回到您的 Activity/fragment (或任何正在实现位置监听器的类)和泄漏金丝雀通知应该消失。

希望这对您有所帮助。

关于android - 从 onPause 中的 fragment 中删除位置更新时发生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43135948/

相关文章:

java - 我的应用程序出现 ANR 问题

android - 从 fragment 中获取适配器中的 Activity 上下文

android - 登录 Google Play 时,应用程序 ID 未与包相关联?

android - Holo 是否有主题,全屏但带有操作栏?

android - 每次禁用设置权限时, Activity 都会重新启动

android - 在 Android 中构建 iBeacon 广告时出现问题

Java (Android Studio) - 无法使用 LocalBroadcastManager.getInstance(this)

android - 在抽屉导航中单击项目时在 viewpager 中切换 fragment

Android Wear 错误 ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null}

android - 谷歌从 Play 商店中删除了应用