Forked from sebaslogen/MyAndroidApplication.kt
Created
August 20, 2023 22:46
Finish all opened activities in my Android app (also across different tasks)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainApplication : Application() { | |
private val createdActivities = mutableListOf<WeakReference<Activity>>() | |
override fun onCreate() { | |
super.onCreate() | |
registerActivityLifecycleCallbacks(activityLifecycleCallbacks()) | |
} | |
fun closeAllActivities() { | |
createdActivities.forEach { | |
it.get()?.finish() | |
} | |
} | |
private fun activityLifecycleCallbacks(): ActivityLifecycleCallbacks { | |
return object : ActivityLifecycleCallbacks { | |
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { | |
if (activity == null) return | |
createdActivities.add(WeakReference(activity)) | |
} | |
override fun onActivityDestroyed(activity: Activity?) { | |
if (activity == null) return | |
createdActivities.removeAll { it.get() == activity } | |
} | |
override fun onActivityPaused(activity: Activity?) {} | |
override fun onActivityResumed(activity: Activity?) {} | |
override fun onActivityStarted(activity: Activity?) {} | |
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {} | |
override fun onActivityStopped(activity: Activity?) {} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment