gpt4 book ai didi

android - LoadedApk$ServiceDispatcher.mContext 正在泄漏

转载 作者:行者123 更新时间:2023-12-04 23:56:07 43 4
gpt4 key购买 nike

经过几次旋转并且应用程序处于后台后,我得到了这个泄漏。这是堆栈跟踪,我无法理解原因。另外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, 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)
备注 我在主要 Activity 中绑定(bind)服务,因为我必须在抽屉中使用自定义选项卡以及一些 fragment 。
增强型NavHostFragment - 在主 Activity 布局内添加
<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 的 native 引用没有被释放。这似乎意味着 IBinder.unleakToDeath() 没有被 LoadedApk 调用。
您应该尝试在最新的 Android 版本上进行重现,看看该错误是否仍然存在。如果是,请在 AOSP 中提交错误。

关于android - LoadedApk$ServiceDispatcher.mContext 正在泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66530882/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com