Skip to content

Instantly share code, notes, and snippets.

@glendmaatita
Last active May 20, 2021 04:05
Show Gist options
  • Save glendmaatita/d870fe19a2875830f917957e28f1dd5f to your computer and use it in GitHub Desktop.
Save glendmaatita/d870fe19a2875830f917957e28f1dd5f to your computer and use it in GitHub Desktop.
Android - Activities Stack Handler
// Manually handle activity stack
// Android has many different mechanism on how to handle activities stack on each version
// Instead rely on native tool, we create this class to handle the stack
//
// How does it work?
//
// Make sure all of your activities is inherited from a `BaseActivity`
// When an activity launched, call `super.onCreate()` method from `BaseActivity`
// `BaseActivity@onCreate` is simple, just call `addActivity(this)` method to add your activity to the stack
// Don't forget to remove it from stack, by calling `removeActivity(this)`, when the activity is destroyed
package com.refactory.sampleapp.app.infrastructures.handlers
import android.app.Activity
import java.util.*
class ActivitiesStackHandler {
private val activities: Stack<Activity> = Stack()
// Make it singleton. Because this will be single source of truth for a whole app
companion object {
private lateinit var instance: ActivitiesStackHandler
fun getInstance(): ActivitiesStackHandler {
if (!::instance.isInitialized) {
instance = ActivitiesStackHandler()
}
return instance
}
}
fun addActivity(activity: Activity) {
activities.add(activity)
}
fun removeActivity(activity: Activity) {
val removed = findActivity(activity.javaClass)
activities.remove(removed)
}
// get current activity, located in top of the stack
fun currentActivity(): Class<*>? {
return if (activities.isEmpty()) null else activities.lastElement()::class.java
}
// Counting how many activities is in the stack right now
fun count(): Int {
return activities.size
}
// find activity by its simple name
fun findActivity(cls: Class<*>): Activity? {
var activity: Activity? = null
for (aClass in activities) {
if (aClass.javaClass == cls) {
activity = aClass
break
}
}
return activity
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment