11package com.dede.android_eggs.util
22
3+ import android.app.Application
4+ import android.content.ComponentCallbacks2
35import android.content.Intent
6+ import android.content.res.Configuration
47import android.os.Bundle
58import android.util.Log
9+ import androidx.collection.ArrayMap
610import androidx.lifecycle.LifecycleOwner
711import androidx.lifecycle.MutableLiveData
812import androidx.lifecycle.Observer
@@ -11,7 +15,7 @@ typealias EventCallback = (intent: Intent) -> Unit
1115
1216object LocalEvent {
1317
14- private val localEventLiveDataMap = HashMap <String , MutableLiveData <Intent ?>>()
18+ private val localEventLiveDataMap = ArrayMap <String , MutableLiveData <Intent ?>>()
1519
1620 private fun getKey (action : String ): String {
1721 return action
@@ -25,21 +29,43 @@ object LocalEvent {
2529 return liveData
2630 }
2731
28- init {
29- GcWatcher .get().addWatcher { trim() }
32+ fun registerTrimMemoryCallback (application : Application ) {
33+ application.registerComponentCallbacks(object : ComponentCallbacks2 {
34+ override fun onConfigurationChanged (newConfig : Configuration ) {
35+ }
36+
37+ override fun onTrimMemory (level : Int ) {
38+ if (level >= ComponentCallbacks2 .TRIM_MEMORY_BACKGROUND ) {
39+ trimToSize(0 )
40+ } else if (level <= ComponentCallbacks2 .TRIM_MEMORY_UI_HIDDEN ) {
41+ trimToSize(localEventLiveDataMap.size / 2 )
42+ }
43+ }
44+
45+ @Deprecated(" Deprecated in Java" )
46+ override fun onLowMemory () {
47+ }
48+ })
3049 }
3150
32- private fun trim ( ) {
33- var count = 0
51+ fun trimToSize ( size : Int ) {
52+ var trimCount = 0
3453 val keys = localEventLiveDataMap.keys
3554 for (key in keys) {
36- val liveData = localEventLiveDataMap[key] ? : continue
55+ val liveData = localEventLiveDataMap[key]
56+ if (liveData == null ) {
57+ localEventLiveDataMap.remove(key)
58+ continue
59+ }
3760 if (! liveData.hasObservers()) {
3861 localEventLiveDataMap.remove(key)
39- count++
62+ trimCount++
63+ }
64+ if (size > 0 && size >= localEventLiveDataMap.size) {
65+ break
4066 }
4167 }
42- Log .i(" LocalEvent" , " trim: %d" .format(count ))
68+ Log .i(" LocalEvent" , " trimToSize, trim: %d" .format(trimCount ))
4369 }
4470
4571 fun poster (): Poster {
0 commit comments