LoadedApk$ServiceDispatcher.mContext 泄漏

问题描述

经过多次轮换和应用程序在后台运行后,我发现此泄漏。这是堆栈跟踪,我无法理解原因。另外 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()
}
....
}

我尝试使用 This Tutorial

实现 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) {
            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" />

解决方法

这看起来像是 Android 框架代码中的漏洞,您可以通过查看 LoadedApk.java 的源代码来发现。

当一个单独的进程连接到您的进程中的服务时,会创建一个 ServiceDispatcher.DeathMonitor。这用于在连接的进程终止时通知 LoadedApk。

这里的泄漏发生是因为服务被破坏了,但不知何故对 DeathMonitor 的本机引用没有被释放。这似乎意味着 IBinder.unleakToDeath() 没有被 LoadedApk 调用。

您应该尝试在最新的 Android 版本上重现,看看错误是否仍然存在。如果是,请在 AOSP 中提交错误。

,

看起来泄漏是由线路引起的:

navController.addOnDestinationChangedListener(this)

在这里,您将 Activity 的实例传递给控制器​​,但在 Activity 被销毁时永远不会将其删除,因此会发生泄漏。

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