Use weak reference to track activity

This commit is contained in:
topjohnwu 2022-06-02 02:18:11 -07:00
parent 47e7a0a434
commit 9ab7550970

View File

@ -1,6 +1,5 @@
package com.topjohnwu.magisk.core
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
@ -15,6 +14,7 @@ import com.topjohnwu.superuser.internal.UiThreadHandler
import com.topjohnwu.superuser.ipc.RootService
import kotlinx.coroutines.Dispatchers
import timber.log.Timber
import java.lang.ref.WeakReference
import kotlin.system.exitProcess
open class App() : Application() {
@ -81,20 +81,21 @@ open class App() : Application() {
}
}
@SuppressLint("StaticFieldLeak")
object ActivityTracker : Application.ActivityLifecycleCallbacks {
val foreground: Activity? get() = ref.get()
@Volatile
var foreground: Activity? = null
private var ref = WeakReference<Activity>(null)
override fun onActivityResumed(activity: Activity) {
if (activity is SuRequestActivity) return
foreground = activity
ref = WeakReference(activity)
}
override fun onActivityPaused(activity: Activity) {
if (activity is SuRequestActivity) return
foreground = null
ref.clear()
}
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {}