LoadedApk$ServiceDispatcher.mContext泄漏了。

5

我在应用程序后台旋转几次后出现了这种内存泄漏。以下是堆栈跟踪,我无法理解其原因。此外,32474006个字节的保留对象太多了。我有10个相同的泄漏。

32474006 bytes retained by leaking objects
Displaying only 1 leak trace out of 10 with the same signature
Signature: 329ec5b3be0cfe3ed2fc888129f5a6be93fb9
┬───
│ GC Root: Global variable in native code
│
├─ android.app.LoadedApk$ServiceDispatcher$DeathMonitor instance
│    Leaking: UNKNOWN
│    ↓ LoadedApk$ServiceDispatcher$DeathMonitor.this$0
│                                               ~~~~~~
├─ android.app.LoadedApk$ServiceDispatcher instance
│    Leaking: UNKNOWN
│    ↓ LoadedApk$ServiceDispatcher.mContext
│                                  ~~~~~~~~
╰→ com.ics.homework.ui.MainActivity instance
​     Leaking: YES (ObjectWatcher was watching this because com.ics.homework.ui.MainActivity received Activity#onDestroy() callback and Activity#mDestroyed is true)
​     key = 8bcc50f8-ea3f-47d9-8dc3-904042a58df4
​     watchDurationMillis = 60220
​     retainedDurationMillis = 55216
====================================
0 LIBRARY LEAKS

泄漏的原因
@AndroidEntryPoint
class MainActivity : AppCompatActivity(), NavController.OnDestinationChangedListener { 

....

override fun onStart() {
    super.onStart()
    findChromeCustomTabsNavigator(navController).bindCustomTabsService()
}
....
}

我尝试使用这篇教程实现Chrome自定义标签页。

@Navigator.Name("chrome")
class ChromeCustomTabsNavigator(
private val context: Context
) : Navigator<ChromeCustomTabsNavigator.Destination>() {

/**
 * Initialized when `findChromeCustomTabsNavigator().bindCustomTabsService()` is called.
 */
private var session: CustomTabsSession? = null

private val urisInProgress = mutableMapOf<Uri, Long>()

private var connection :CustomTabsServiceConnection?= null

/**
 * Prevent the user from repeatedly launching Chrome Custom Tabs for the same URL. Throttle
 * rapid repeats unless the URL has finished loading, or this timeout has passed (just in
 * case something went wrong with detecting that the page finished loading).
 * Feel free to change this value with [Fragment.findChromeCustomTabsNavigator.throttleTimeout()]
 * if you feel the need, or for testing purposes.
 * Defaults to two seconds.
 */
@SuppressWarnings("WeakerAccess")
var throttleTimeout: Long = 2000L

private val upIconBitmap: Bitmap by lazy {
    AppCompatResources.getDrawable(context, R.drawable.ic_baseline_keyboard_backspace_24)?.toBitmap()!!
}

override fun createDestination() =
    Destination(this)

override fun navigate(
    destination: Destination, args: Bundle?, navOptions: NavOptions?, navigatorExtras: Extras?
): NavDestination? {
    // The Navigation framework enforces the destination URL being non-null
    val uri = args?.getParcelable<Uri>(KEY_URI)!!

    if (!shouldAllowLaunch(uri)) return null

    buildCustomTabsIntent(destination).launchUrl(context, uri)

    return null // Do not add to the back stack, managed by Chrome Custom Tabs
}

override fun popBackStack() = true // Managed by Chrome Custom Tabs

private fun buildCustomTabsIntent(destination: Destination): CustomTabsIntent {
    val builder = CustomTabsIntent.Builder()
    val params = CustomTabColorSchemeParams.Builder()

    session?.let { builder.setSession(it) }
    builder.setColorScheme(destination.colorScheme)
    if (destination.toolbarColor != 0) {
        params.setToolbarColor(ContextCompat.getColor(context, destination.toolbarColor))
    }
    if (destination.navigationBarColor != 0) {
        params.setNavigationBarColor(ContextCompat.getColor(context, destination.navigationBarColor))
    }
    builder.setDefaultColorSchemeParams(params.build())
    builder.setStartAnimations(context, destination.enterAnim, destination.popEnterAnim)
    builder.setExitAnimations(context, destination.popExitAnim, destination.exitAnim)
    builder.setShowTitle(destination.showTitle)
    if (destination.upInsteadOfClose) {
        builder.setCloseButtonIcon(upIconBitmap)
    }
    if (destination.addDefaultShareMenuItem) {
        builder.setShareState(CustomTabsIntent.SHARE_STATE_ON)
    }
    val customTabsIntent = builder.build()

    // Adding referrer so websites know where their traffic came from, per Google's recommendations:
    // https://medium.com/google-developers/best-practices-for-custom-tabs-5700e55143ee
    customTabsIntent.intent.putExtra(
        Intent.EXTRA_REFERRER, Uri.parse("android-app://" + context.packageName)
    )
    return customTabsIntent
}

private fun shouldAllowLaunch(uri: Uri): Boolean {
    urisInProgress[uri]?.let { tabStartTime ->
        // Have we launched this URI before recently?
        if (System.currentTimeMillis() - tabStartTime > throttleTimeout) {
            // Since we've exceeded the throttle timeout, continue as normal, launching
            // the destination and updating the time.
            Timber.w("Throttle timeout for $uri exceeded. This means ChromeCustomTabsNavigator failed to accurately determine that the URL finished loading. If you see this error frequently, it could indicate a bug in ChromeCustomTabsNavigator.")
        } else {
            // The user has tried to repeatedly open the same URL in rapid succession. Let them chill.
            // The tab probably just hasn't opened yet. Abort opening the tab a second time.
            urisInProgress.remove(uri)
            return false
        }
    }
    urisInProgress[uri] = System.currentTimeMillis()
    return true
}

/**
 * Boilerplate setup for Chrome Custom Tabs. This should suffice for most apps using Chrome
 * Custom Tabs with the Navigation component. It warms up Chrome in advance to save a few
 * milliseconds, and sets a [CustomTabsSession] for the [ChromeCustomTabsNavigator] so that
 * [CustomTabsSession.mayLaunchUrl] can be called from application code.
 */
fun bindCustomTabsService() {
    connection = object : CustomTabsServiceConnection() {
        override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) {
            client.warmup(0L)
            session = client.newSession(customTabsCallback)
            //context.unbindService(this)
        }

        override fun onServiceDisconnected(name: ComponentName?) {}
    }
    CustomTabsClient.bindCustomTabsService(context, CUSTOM_TAB_PACKAGE_NAME, connection!!)
}

fun unBindCustomTabsService(){
    if(connection !=null) return
    context.unbindService(connection!!)
}

/**
 * Possibly pre-load one or more URLs. Note that
 * per https://developer.chrome.com/multidevice/android/customtabs#pre-render-content,
 * mayLaunchUrl should only be used if the odds are at least 50% of the user clicking
 * the link.
 * @see [CustomTabsSession.mayLaunchUrl] for more details on mayLaunchUrl.
 */
fun mayLaunchUrl(url: Uri, extras: Bundle? = null, otherLikelyBundles: List<Bundle>? = null) {
    session?.mayLaunchUrl(url, extras, otherLikelyBundles)
}

val customTabsCallback: CustomTabsCallback by lazy {
    object : CustomTabsCallback() {
        override fun onNavigationEvent(navigationEvent: Int, extras: Bundle?) {
            when (navigationEvent) {
                NAVIGATION_ABORTED, NAVIGATION_FAILED, NAVIGATION_FINISHED -> {
                    // Navigation has finished. Remove the indication that page has not finished
                    // loading, so we will allow the user to try to open the same page again.
                    with(urisInProgress.entries) {
                        remove(first())
                    }
                }
            }
        }
    }
}

companion object {
    private const val TAG = "ChromeTabsNavigator"
    private const val CUSTOM_TAB_PACKAGE_NAME = "com.android.chrome"
    const val KEY_URI = "uri"
}

@NavDestination.ClassType(Activity::class)
class Destination(navigator: Navigator<out NavDestination>) : NavDestination(navigator) {

    var colorScheme: Int = 1

    @ColorRes
    var toolbarColor: Int = 0

    @ColorRes
    var navigationBarColor: Int = 0

    @AnimRes
    var enterAnim: Int = 0

    @AnimRes
    var exitAnim: Int = 0

    @AnimRes
    var popEnterAnim: Int = 0

    @AnimRes
    var popExitAnim: Int = 0

    var showTitle: Boolean = false

    var upInsteadOfClose: Boolean = false

    var addDefaultShareMenuItem: Boolean = false

    override fun onInflate(context: Context, attrs: AttributeSet) {
        super.onInflate(context, attrs)

        context.withStyledAttributes(attrs, R.styleable.ChromeCustomTabsNavigator, 0, 0) {
            colorScheme = getInt(R.styleable.ChromeCustomTabsNavigator_colorScheme, 0)
            toolbarColor = getResourceId(R.styleable.ChromeCustomTabsNavigator_toolbarColor, 0)
            navigationBarColor =
                getResourceId(R.styleable.ChromeCustomTabsNavigator_navigationBarColor, 0)
            enterAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_enterAnim, 0)
            exitAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_exitAnim, 0)
            popEnterAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_popEnterAnim, 0)
            popExitAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_popExitAnim, 0)
            showTitle = getBoolean(R.styleable.ChromeCustomTabsNavigator_showTitle, false)
            upInsteadOfClose =
                getBoolean(R.styleable.ChromeCustomTabsNavigator_upInsteadOfClose, false)
            addDefaultShareMenuItem =
                getBoolean(R.styleable.ChromeCustomTabsNavigator_addDefaultShareMenuItem, false)
        }
    }
}
}
/**
 * From https://proandroiddev.com/add-chrome-custom-tabs-to-the-android-navigation-component-75092ce20c6a
 */
class EnhancedNavHostFragment : NavHostFragment() {
@SuppressLint("RestrictedApi")
override fun onCreateNavController(navController: NavController) {
    super.onCreateNavController(navController)
    context?.let { navController.navigatorProvider += ChromeCustomTabsNavigator(it) }
}
}

扩展函数

fun Fragment.findChromeCustomTabsNavigator(): ChromeCustomTabsNavigator =
findNavController().navigatorProvider.getNavigator(ChromeCustomTabsNavigator::class.java)

fun AppCompatActivity.findChromeCustomTabsNavigator(navController: NavController): ChromeCustomTabsNavigator =
navController.navigatorProvider.getNavigator(ChromeCustomTabsNavigator::class.java)

注意:我在主活动中绑定服务,因为我需要在抽屉中使用自定义选项卡以及一些片段。

EnhancedNavHostFragment - 添加到主活动布局中。

<androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragmentContainerView"
            android:name="com.ics.homework.utils.EnhancedNavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/toolbar"
            app:navGraph="@navigation/main_nav_graph" />

在初始化 ChromeCustomTabsNavigator 时(在教程中是在 EnhancedNavHostFragment 中完成的),你是否尝试传入应用程序上下文? - Henry Twist
EnhancedNavHostFragmentnavController 获取上下文。 - Abhishek Singh
你能在你的问题中添加 EnhancedNavHostFragment 吗? - Henry Twist
@HenryTwist 已添加。 - Abhishek Singh
@HenryTwist,请查看下面的自定义选项卡类。 - Abhishek Singh
显示剩余9条评论
2个回答

6
这似乎是 Android 框架代码中的泄漏问题,你可以通过查看 LoadedApk.java 的源代码来找到原因。
当单独的进程连接到您的进程中的服务时,会创建一个 ServiceDispatcher.DeathMonitor。这用于在连接的进程死亡时通知 LoadedApk。
这里发生泄漏的原因是服务被销毁,但是某种方式未释放对 DeathMonitor 的本机引用。这似乎意味着 LoadedApk 没有调用 IBinder.unleakToDeath()。
您应该尝试在最新的 Android 发布版上进行复现并查看是否仍存在此问题。如果是,请在 AOSP 上提交错误报告。

0

看起来泄漏是由这行代码引起的:

navController.addOnDestinationChangedListener(this)

在这里,您将您的活动实例传递给控制器,但在活动被销毁时从未删除它,因此会出现泄漏。

我建议在onResume中添加侦听器,并在onPause中删除它。


我已经在 onResume 中添加了 navController.addOnDestinationChangedListener(this),并在 onPause 中添加了 navController.removeOnDestinationChangedListener(this)。但是我仍然遇到了泄漏问题。 - Abhishek Singh
我猜你已经在onCreate中删除了原始调用了吧? - Henry Twist
我建议将你的活动简化到基础功能,然后逐行添加代码,这样应该能够相对快速地找到问题所在。 - Henry Twist
好的,我找到了我的问题并更新了问题。 - Abhishek Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接