android 带有导航组件的活动在启动新根活动或调用Finish()后导致内存泄漏

yrdbyhpb  于 2023-03-27  发布在  Android
关注(0)|答案(1)|浏览(112)

我的应用程序从Activity**_ A _**开始,其中包含如下初始化的FragmentContainer

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainView"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/register_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        tools:layout="@layout/fragment_login"
        tools:ignore="FragmentTagUsage" />
</androidx.constraintlayout.widget.ConstraintLayout>
private var navHostFragment: NavHostFragment? = null
    private var navController: NavController? = null
    private fun setNavGraph() {
        navHostFragment = supportFragmentManager.findFragmentById(R.id.register_nav_host_fragment) as NavHostFragment            
        navController = navHostFragment?.navController
        val graph = navController?.navInflater?.inflate(R.navigation.registration_process_graph)
        navController?.setGraph(graph !!, intent.extras)
 
    }

现在,当我尝试以root身份打开新活动时,出现内存泄漏
一个二个一个一个
请注意,在移动到DashboardActivity之前,我已尝试删除所有子视图并清除Activity _A_的局部变量,如下所示

navHostFragment = null
        navController = null
         val navView = findViewById<FrameLayout>(R.id.register_nav_host_fragment)
        (navView.parent as ViewManager).removeView(navView)
vmpqdwk3

vmpqdwk31#

你的泄漏金丝雀日志看起来werid。

├─ android.widget.FrameLayout instance
│    Leaking: YES (View.mContext references a destroyed activity)
│    Retaining 89.6 kB in 1750 objects
│    View is part of a window view hierarchy
│    View.mAttachInfo is null (view detached)
│    View.mID = R.id.null
│    View.mWindowAttachCount = 0
│    mContext instance of android.view.ContextThemeWrapper, wrapping activity

FrameLayout是分离的,但它也是窗口视图层次结构的一部分。这是怎么可能的?我不确定,但你是直接将FrameLayout添加到窗口还是像这样使用WindowManager

// using window API
window.addContentView(FrameLayout(this), null)
// using acitivity API
this@MainActivity.addContentView(FrameLayout(this), null)
// using WindowManager API
windowManager.addView(FrameLayout(this), ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))

相关问题