如何通过 Activity 中发生的点击事件关闭 Fragment 中的会话

问题描述 投票:0回答:1

我继承了一个视频播放应用程序,我需要向其中添加分析。在我的片段中,我创建了分析对象,然后该对象侦听并报告事件和数据。如果用户单击父活动的回收器视图中的另一个项目,我需要能够触发当前片段的会话结束。

我尝试在我的活动中创建片段的实例并从单击事件调用该方法,但该方法从未被调用并且会话继续:

VideoFragment videoFragment = new VideoFragment();
videoFragment.endSession();

如何在我的活动片段中结束此会话?

更新:我也在父活动中尝试过此操作,但应用程序崩溃了。

FragmentManager fm = getSupportFragmentManager();
VideoFragment videoFrag = (VideoFragment) fm.findFragmentByTag("VideoFragment");
if (videoFrag != null) {
    videoFrag.endSession();
            }  
android android-fragments android-activity android-lifecycle
1个回答
0
投票

片段可以根据自己的生命周期管理自己的分析。在片段的 onCreate() 中:

// Initialized and start the analytics
startSession()

在 onDestroy() 中:

// Stop the session and remove reference to it
endSession();
© www.soinside.com 2019 - 2024. All rights reserved.