Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Finish all opened activities in my Android app (also across different tasks)
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
You can’t perform that action at this time.