Show Back Stack of Android

前端 未结 3 1407
执念已碎
执念已碎 2021-02-02 13:10

For better understanding the behavior of Android I\'d like to learn more about the back stack concept. Is there a way to list all activities as they are ordered in back stack. T

3条回答
  •  甜味超标
    2021-02-02 13:42

    For the back stack of your own app, you can write your own solution 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>()
    
            fun getCurrentActivityStack() = listOf(activityStack)
    
            fun install(app: Application) {
                app.registerActivityLifecycleCallbacks(ActivityBackStackTracker())
            }
        }
    }
    

    Then at any moment you can log it with:

    Log.d(TAG, "${ActivityBackStackTracker.getCurrentActivityStack()})
    

提交回复
热议问题