因为Jetpack导航中没有使用片段,所以我想观察Jetpack navigator的生命周期,以获得当前目的地或屏幕名称。正如您所知,Jetpack导航不是使用碎片,而是使用深度链接结构。我找了很多,但找不到合适的解决方案。
我想获得我的sdk的路线或目的地名称,以跟踪屏幕流。
class AppLifeCycleObserver : Application.ActivityLifecycleCallbacks {
var route: String? = ""
override fun onActivityCreated(p0: Activity, p1: Bundle?) {
log("onActivityCreated")
}
val TAG = "AppLifeCycleObserver"
fun log(message: String) {
Log.e(TAG, message)
}
override fun onActivityStarted(p0: Activity) {
log("onActivityStarted")
if (p0 is FragmentActivity) {
p0.supportFragmentManager.registerFragmentLifecycleCallbacks(object :
FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentCreated(
fm: FragmentManager,
f: Fragment,
savedInstanceState: Bundle?
) {
super.onFragmentCreated(fm, f, savedInstanceState)
log("onFragmentCreated")
}
override fun onFragmentDestroyed(fm: FragmentManager, f: Fragment) {
super.onFragmentDestroyed(fm, f)
log("onFragmentDestroyed")
}
}, true)
} else if (p0 is ComponentActivity) {
(p0 as MasterActivity).navController_field.currentBackStackEntry.destination.route
log("ComponentActivity")
}
}
override fun onActivityResumed(p0: Activity) {
log("onActivityResumed")
}
override fun onActivityPaused(p0: Activity) {
log("onActivityPaused")
}
override fun onActivityStopped(p0: Activity) {
log("onActivityStopped")
}
override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
}
override fun onActivityDestroyed(p0: Activity) {
log("onActivityDestroyed")
}
}
我无法访问
(p0 as MasterActivity).navController_field.currentBackStackEntry.destination.route
因为这是不可访问的,我通过调试找到了它
navController
初始化不必是活动的公共字段。在谷歌文档中,用户需要在活动setContent((中调用rememberNavController()
,仅此而已
因此,也许你可以要求SDK的用户提供navHostController作为初始化参数,或者这不是一个选项?