How to view the Back Stack programmatically?

438 Views Asked by At

I'm trying to create an app ("ShowStack") to view the current App Back Stack (for development purposes). I know it can be done by using adb with the command "adb shell dumpsys activity activities". I tried using ActivityManager functions getAppTasks() and getRunningProcesses, etc. But these only return a list of 1 item, the current app/task "ShowStack", which I already knew thank you.

How can I view all tasks/activities?

2

There are 2 best solutions below

1
On

There's no API that lets you peek the whole backstack. Unless you are targeting rooted devices, you are most likely out of luck as there's no way to inspect that for security/privacy reasons.

0
On

You can write your own using Application.ActivityLifecycleCallbacks:

class MyApp : Application() {
   
   override fun onCreate() {
      super.onCreate()
      ActivityBackStackTracker.install(this)
   }
}

class ActivityBackStackTracker : Application.ActivityLifecycleCallbacks {

    override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
        activityStack.add(activity::class)
    }

    override fun onActivityDestroyed(activity: Activity) {
        activityStack.remove(activity::class)
    }

    //..

    companion object {
        private val activityStack = mutableListOf<KClass<out Activity>>()

        fun getCurrentActivityStack() = listOf(activityStack)

        fun install(app: Application) {
            app.registerActivityLifecycleCallbacks(ActivityBackStackTracker())
        }
    }
}