是否有一种方法可以避免触发不止一次的NativeScript活动生命周期事件



我尝试使用以下指南在我的Nativescript Android应用中处理Android Lifecycle:https://docs.nativecript.org/core-concepts/application-lifecycle-clecle-clocycle-android-activity-events

当我使用返回按钮退出应用程序然后重新打开应用程序的最新按钮时,所有生命周期事件都会触发两次。如果我再次进行ti,所有生命周期事件都是触发的三次。

这是一个游乐场简单的应用程序,显示了问题:https://play.nativecript.org/?template=play-ng& id=y9rucd

使用后面按钮,然后使用最新按钮恢复...

您需要在销毁事件中删除听众。当您使用android.on分配事件侦听器时,您也需要使用android.off

您可以在这里和这里找到一个完整的示例。我还更新了您的操场。

在您的ngoninit函数中,我将android.on分配给听众,例如

this.launchListenerCB = (args) => {
            console.log(">>>>>>> resumeEvent Event");
            if (args.android) {
                // For Android applications, args.android is an android.content.Intent class.
                console.log("resumeEvent Android application with the following intent: " + args.android + ".");
            }
        };
        appOn(resumeEvent, this.launchListenerCB);

,在ExiteVent上,我正在订阅所有听众。

this.exitListenerCB = (eventData: any) => {
            this.unsubscribeAll();
        }
        appOn(exitEvent, this.exitListenerCB);

private unsubscribeAll(): void {
        // console.log("unsubscribeAll launchListenerCB:", !!launchListenerCB)
        appOff(resumeEvent, this.launchListenerCB); // HERE
        // appOff(suspendEvent, this.suspendListenerCB);
        // appOff(resumeEvent, this.resumeListenerCB);
        // appOff(lowMemoryEvent, this.lowMemoryListenerCB);
        // appOff(exitEvent, this.exitListenerCB);
    }

在您的操场上,我刚刚使用resumeevent向您展示代码,您也可以分配/统一到其他事件。

最新更新