diff --git a/basic/src/main/java/com/dede/android_eggs/util/GcWatcher.kt b/basic/src/main/java/com/dede/android_eggs/util/GcWatcher.kt new file mode 100644 index 00000000..b4e18f9a --- /dev/null +++ b/basic/src/main/java/com/dede/android_eggs/util/GcWatcher.kt @@ -0,0 +1,50 @@ +package com.dede.android_eggs.util + +import java.lang.ref.WeakReference + +/** + * GC Watcher + * + * @see [com.android.internal.os.BinderInternal] + */ +class GcWatcher private constructor() { + + companion object { + + private val sInstance = GcWatcher() + + private val sGcWatchers: ArrayList = ArrayList() + private var sTempWatchers: Array = emptyArray() + + private var sGcWatcherRef: WeakReference = WeakReference(GcWatcherObj()) + + fun get(): GcWatcher { + return sInstance + } + } + + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") + private class GcWatcherObj : Object() { + override fun finalize() { + synchronized(sGcWatchers) { + sTempWatchers = sGcWatchers.toArray(sTempWatchers) + } + for (gcWatcher in sTempWatchers) { + gcWatcher?.run() + } + sGcWatcherRef = WeakReference(GcWatcherObj()) + } + } + + fun addWatcher(watcher: Runnable) { + synchronized(sGcWatchers) { + sGcWatchers.add(watcher) + } + } + + fun removeWatcher(watcher: Runnable) { + synchronized(sGcWatchers) { + sGcWatchers.remove(watcher) + } + } +} diff --git a/basic/src/main/java/com/dede/android_eggs/util/LocalEvent.kt b/basic/src/main/java/com/dede/android_eggs/util/LocalEvent.kt index 8deb2208..c39fd501 100644 --- a/basic/src/main/java/com/dede/android_eggs/util/LocalEvent.kt +++ b/basic/src/main/java/com/dede/android_eggs/util/LocalEvent.kt @@ -2,6 +2,7 @@ package com.dede.android_eggs.util import android.content.Intent import android.os.Bundle +import android.util.Log import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer @@ -24,6 +25,23 @@ object LocalEvent { return liveData } + init { + GcWatcher.get().addWatcher { trim() } + } + + private fun trim() { + var count = 0 + val keys = localEventLiveDataMap.keys + for (key in keys) { + val liveData = localEventLiveDataMap[key] ?: continue + if (!liveData.hasObservers()) { + localEventLiveDataMap.remove(key) + count++ + } + } + Log.i("LocalEvent", "trim: %d".format(count)) + } + fun poster(): Poster { return Poster() }