Skip to content

Instantly share code, notes, and snippets.

@ravisorathiya
Created April 4, 2024 07:32
Show Gist options
  • Save ravisorathiya/667c4ed6ee73b741328713e0a45492ae to your computer and use it in GitHub Desktop.
Save ravisorathiya/667c4ed6ee73b741328713e0a45492ae to your computer and use it in GitHub Desktop.
ActivityTracker.kt
class ActivityTracker private constructor(private val context: Application) {
private val runningActivities = LinkedHashSet<Activity>()
private val exceptActivity = LinkedHashSet<Class<*>>()
private val trackOnlyActivities = LinkedHashSet<Class<*>>()
private var trackRegisterOnly = false
companion object {
@Volatile
private var INSTANCE: ActivityTracker? = null
fun getInstance(context: Application): ActivityTracker {
return INSTANCE ?: synchronized(this) {
val instance = INSTANCE
if (instance == null) {
INSTANCE = ActivityTracker(context)
}
INSTANCE!!
}
}
}
/**
* Register the track of an open activity and closed in the application
* */
fun build() {
context.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
when {
trackRegisterOnly -> {
trackOnlyActivities.forEach {
if (it.isInstance(activity)) {
runningActivities.add(activity)
}
}
}
exceptActivity.any { it.isInstance(activity) } -> {
return
}
else -> {
runningActivities.add(activity)
}
}
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
runningActivities.remove(activity)
}
})
}
/**
* @param clazz - Activity class to be tracked
* @sample (MainActivity::class.java,SplashActivity::class.java)
* */
fun only(vararg clazz: Class<*>): ActivityTracker {
trackRegisterOnly = true
trackOnlyActivities.addAll(clazz)
return this
}
/**
* @param clazz - Activity class to be excluded from tracking for example (MainActivity::class.java,SplashActivity::class.java)
* */
fun except(vararg clazz: Class<*>): ActivityTracker {
trackRegisterOnly = false
exceptActivity.addAll(clazz)
return this
}
fun recreateActivities() {
runningActivities.forEach { activity -> ActivityCompat.recreate(activity) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment