Abh*_*ngh 5 android leakcanary
经过多次轮换并且应用程序处于后台后,我收到此泄漏。这是堆栈跟踪,我无法理解原因。另外32474006字节保留的对象非常多。我有 10 个相同的泄漏。
\n32474006 bytes retained by leaking objects\nDisplaying only 1 leak trace out of 10 with the same signature\nSignature: 329ec5b3be0cfe3ed2fc888129f5a6be93fb9\n\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n\xe2\x94\x82 GC Root: Global variable in native code\n\xe2\x94\x82\n\xe2\x94\x9c\xe2\x94\x80 android.app.LoadedApk$ServiceDispatcher$DeathMonitor instance\n\xe2\x94\x82 Leaking: UNKNOWN\n\xe2\x94\x82 \xe2\x86\x93 LoadedApk$ServiceDispatcher$DeathMonitor.this$0\n\xe2\x94\x82 ~~~~~~\n\xe2\x94\x9c\xe2\x94\x80 android.app.LoadedApk$ServiceDispatcher instance\n\xe2\x94\x82 Leaking: UNKNOWN\n\xe2\x94\x82 \xe2\x86\x93 LoadedApk$ServiceDispatcher.mContext\n\xe2\x94\x82 ~~~~~~~~\n\xe2\x95\xb0\xe2\x86\x92 com.ics.homework.ui.MainActivity instance\n\xe2\x80\x8b Leaking: YES (ObjectWatcher was watching this because com.ics.homework.ui.MainActivity received Activity#onDestroy() callback and Activity#mDestroyed is true)\n\xe2\x80\x8b key = 8bcc50f8-ea3f-47d9-8dc3-904042a58df4\n\xe2\x80\x8b watchDurationMillis = 60220\n\xe2\x80\x8b retainedDurationMillis = 55216\n====================================\n0 LIBRARY LEAKS\nRun Code Online (Sandbox Code Playgroud)\n泄漏原因
\n@AndroidEntryPoint\nclass MainActivity : AppCompatActivity(), NavController.OnDestinationChangedListener { \n\n....\n\noverride fun onStart() {\n super.onStart()\n findChromeCustomTabsNavigator(navController).bindCustomTabsService()\n}\n....\n}\nRun Code Online (Sandbox Code Playgroud)\n我尝试使用本教程实现 Chrome 自定义选项卡
\n@Navigator.Name("chrome")\nclass ChromeCustomTabsNavigator(\nprivate val context: Context\n) : Navigator<ChromeCustomTabsNavigator.Destination>() {\n\n/**\n * Initialized when `findChromeCustomTabsNavigator().bindCustomTabsService()` is called.\n */\nprivate var session: CustomTabsSession? = null\n\nprivate val urisInProgress = mutableMapOf<Uri, Long>()\n\nprivate var connection :CustomTabsServiceConnection?= null\n\n/**\n * Prevent the user from repeatedly launching Chrome Custom Tabs for the same URL. Throttle\n * rapid repeats unless the URL has finished loading, or this timeout has passed (just in\n * case something went wrong with detecting that the page finished loading).\n * Feel free to change this value with [Fragment.findChromeCustomTabsNavigator.throttleTimeout()]\n * if you feel the need, or for testing purposes.\n * Defaults to two seconds.\n */\n@SuppressWarnings("WeakerAccess")\nvar throttleTimeout: Long = 2000L\n\nprivate val upIconBitmap: Bitmap by lazy {\n AppCompatResources.getDrawable(context, R.drawable.ic_baseline_keyboard_backspace_24)?.toBitmap()!!\n}\n\noverride fun createDestination() =\n Destination(this)\n\noverride fun navigate(\n destination: Destination, args: Bundle?, navOptions: NavOptions?, navigatorExtras: Extras?\n): NavDestination? {\n // The Navigation framework enforces the destination URL being non-null\n val uri = args?.getParcelable<Uri>(KEY_URI)!!\n\n if (!shouldAllowLaunch(uri)) return null\n\n buildCustomTabsIntent(destination).launchUrl(context, uri)\n\n return null // Do not add to the back stack, managed by Chrome Custom Tabs\n}\n\noverride fun popBackStack() = true // Managed by Chrome Custom Tabs\n\nprivate fun buildCustomTabsIntent(destination: Destination): CustomTabsIntent {\n val builder = CustomTabsIntent.Builder()\n val params = CustomTabColorSchemeParams.Builder()\n\n session?.let { builder.setSession(it) }\n builder.setColorScheme(destination.colorScheme)\n if (destination.toolbarColor != 0) {\n params.setToolbarColor(ContextCompat.getColor(context, destination.toolbarColor))\n }\n if (destination.navigationBarColor != 0) {\n params.setNavigationBarColor(ContextCompat.getColor(context, destination.navigationBarColor))\n }\n builder.setDefaultColorSchemeParams(params.build())\n builder.setStartAnimations(context, destination.enterAnim, destination.popEnterAnim)\n builder.setExitAnimations(context, destination.popExitAnim, destination.exitAnim)\n builder.setShowTitle(destination.showTitle)\n if (destination.upInsteadOfClose) {\n builder.setCloseButtonIcon(upIconBitmap)\n }\n if (destination.addDefaultShareMenuItem) {\n builder.setShareState(CustomTabsIntent.SHARE_STATE_ON)\n }\n val customTabsIntent = builder.build()\n\n // Adding referrer so websites know where their traffic came from, per Google\'s recommendations:\n // https://medium.com/google-developers/best-practices-for-custom-tabs-5700e55143ee\n customTabsIntent.intent.putExtra(\n Intent.EXTRA_REFERRER, Uri.parse("android-app://" + context.packageName)\n )\n return customTabsIntent\n}\n\nprivate fun shouldAllowLaunch(uri: Uri): Boolean {\n urisInProgress[uri]?.let { tabStartTime ->\n // Have we launched this URI before recently?\n if (System.currentTimeMillis() - tabStartTime > throttleTimeout) {\n // Since we\'ve exceeded the throttle timeout, continue as normal, launching\n // the destination and updating the time.\n 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.")\n } else {\n // The user has tried to repeatedly open the same URL in rapid succession. Let them chill.\n // The tab probably just hasn\'t opened yet. Abort opening the tab a second time.\n urisInProgress.remove(uri)\n return false\n }\n }\n urisInProgress[uri] = System.currentTimeMillis()\n return true\n}\n\n/**\n * Boilerplate setup for Chrome Custom Tabs. This should suffice for most apps using Chrome\n * Custom Tabs with the Navigation component. It warms up Chrome in advance to save a few\n * milliseconds, and sets a [CustomTabsSession] for the [ChromeCustomTabsNavigator] so that\n * [CustomTabsSession.mayLaunchUrl] can be called from application code.\n */\nfun bindCustomTabsService() {\n connection = object : CustomTabsServiceConnection() {\n override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) {\n client.warmup(0L)\n session = client.newSession(customTabsCallback)\n //context.unbindService(this)\n }\n\n override fun onServiceDisconnected(name: ComponentName?) {}\n }\n CustomTabsClient.bindCustomTabsService(context, CUSTOM_TAB_PACKAGE_NAME, connection!!)\n}\n\nfun unBindCustomTabsService(){\n if(connection !=null) return\n context.unbindService(connection!!)\n}\n\n/**\n * Possibly pre-load one or more URLs. Note that\n * per https://developer.chrome.com/multidevice/android/customtabs#pre-render-content,\n * mayLaunchUrl should only be used if the odds are at least 50% of the user clicking\n * the link.\n * @see [CustomTabsSession.mayLaunchUrl] for more details on mayLaunchUrl.\n */\nfun mayLaunchUrl(url: Uri, extras: Bundle? = null, otherLikelyBundles: List<Bundle>? = null) {\n session?.mayLaunchUrl(url, extras, otherLikelyBundles)\n}\n\nval customTabsCallback: CustomTabsCallback by lazy {\n object : CustomTabsCallback() {\n override fun onNavigationEvent(navigationEvent: Int, extras: Bundle?) {\n when (navigationEvent) {\n NAVIGATION_ABORTED, NAVIGATION_FAILED, NAVIGATION_FINISHED -> {\n // Navigation has finished. Remove the indication that page has not finished\n // loading, so we will allow the user to try to open the same page again.\n with(urisInProgress.entries) {\n remove(first())\n }\n }\n }\n }\n }\n}\n\ncompanion object {\n private const val TAG = "ChromeTabsNavigator"\n private const val CUSTOM_TAB_PACKAGE_NAME = "com.android.chrome"\n const val KEY_URI = "uri"\n}\n\n@NavDestination.ClassType(Activity::class)\nclass Destination(navigator: Navigator<out NavDestination>) : NavDestination(navigator) {\n\n var colorScheme: Int = 1\n\n @ColorRes\n var toolbarColor: Int = 0\n\n @ColorRes\n var navigationBarColor: Int = 0\n\n @AnimRes\n var enterAnim: Int = 0\n\n @AnimRes\n var exitAnim: Int = 0\n\n @AnimRes\n var popEnterAnim: Int = 0\n\n @AnimRes\n var popExitAnim: Int = 0\n\n var showTitle: Boolean = false\n\n var upInsteadOfClose: Boolean = false\n\n var addDefaultShareMenuItem: Boolean = false\n\n override fun onInflate(context: Context, attrs: AttributeSet) {\n super.onInflate(context, attrs)\n\n context.withStyledAttributes(attrs, R.styleable.ChromeCustomTabsNavigator, 0, 0) {\n colorScheme = getInt(R.styleable.ChromeCustomTabsNavigator_colorScheme, 0)\n toolbarColor = getResourceId(R.styleable.ChromeCustomTabsNavigator_toolbarColor, 0)\n navigationBarColor =\n getResourceId(R.styleable.ChromeCustomTabsNavigator_navigationBarColor, 0)\n enterAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_enterAnim, 0)\n exitAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_exitAnim, 0)\n popEnterAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_popEnterAnim, 0)\n popExitAnim = getResourceId(R.styleable.ChromeCustomTabsNavigator_popExitAnim, 0)\n showTitle = getBoolean(R.styleable.ChromeCustomTabsNavigator_showTitle, false)\n upInsteadOfClose =\n getBoolean(R.styleable.ChromeCustomTabsNavigator_upInsteadOfClose, false)\n addDefaultShareMenuItem =\n getBoolean(R.styleable.ChromeCustomTabsNavigator_addDefaultShareMenuItem, false)\n }\n }\n}\n}\n/**\n * From https://proandroiddev.com/add-chrome-custom-tabs-to-the-android-navigation-component-75092ce20c6a\n */\nclass EnhancedNavHostFragment : NavHostFragment() {\n@SuppressLint("RestrictedApi")\noverride fun onCreateNavController(navController: NavController) {\n super.onCreateNavController(navController)\n context?.let { navController.navigatorProvider += ChromeCustomTabsNavigator(it) }\n}\n}\nRun Code Online (Sandbox Code Playgroud)\n扩展功能
\nfun Fragment.findChromeCustomTabsNavigator(): ChromeCustomTabsNavigator =\nfindNavController().navigatorProvider.getNavigator(ChromeCustomTabsNavigator::class.java)\n\nfun AppCompatActivity.findChromeCustomTabsNavigator(navController: NavController): ChromeCustomTabsNavigator =\nnavController.navigatorProvider.getNavigator(ChromeCustomTabsNavigator::class.java)\nRun Code Online (Sandbox Code Playgroud)\n请注意,我在主要活动中绑定服务,因为我必须在抽屉以及一些片段中使用自定义选项卡。
\n增强的NavHostFragment - 添加到主活动布局内部
\n<androidx.fragment.app.FragmentContainerView\n android:id="@+id/fragmentContainerView"\n android:name="com.ics.homework.utils.EnhancedNavHostFragment"\n android:layout_width="match_parent"\n android:layout_height="match_parent"\n app:defaultNavHost="true"\n app:layout_constraintBottom_toBottomOf="parent"\n app:layout_constraintEnd_toEndOf="parent"\n app:layout_constraintStart_toStartOf="parent"\n app:layout_constraintTop_toBottomOf="@id/toolbar"\n app:navGraph="@navigation/main_nav_graph" />\nRun Code Online (Sandbox Code Playgroud)\n
这看起来像是 Android 框架代码中的泄漏,您可以通过查看LoadedApk.java的源代码来弄清楚。
当单独的进程连接到进程中的服务时,将创建 ServiceDispatcher.DeathMonitor。这用于在连接的进程终止时通知 LoadedApk。
这里发生泄漏是因为服务被破坏,但不知何故,对 DeathMonitor 的本机引用没有被释放。这似乎意味着 IBinder.unleakToDeath() 没有被 LoadedApk 调用。
您应该尝试在最新的 Android 版本上重现并查看该错误是否仍然存在。如果是,请在 AOSP 中提交错误。
看起来泄漏是由线路引起的:
navController.addOnDestinationChangedListener(this)
Run Code Online (Sandbox Code Playgroud)
在这里,您将活动的实例传递给控制器,但在活动被销毁时永远不会删除它,因此会发生泄漏。
我建议将侦听器添加到 中onResume,然后将其删除onPause。
| 归档时间: |
|
| 查看次数: |
1606 次 |
| 最近记录: |