首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否有办法避免多次触发nativescript活动生命周期事件

是否有办法避免多次触发nativescript活动生命周期事件
EN

Stack Overflow用户
提问于 2019-07-04 15:38:17
回答 1查看 578关注 0票数 0

我尝试使用以下指南在我的NativeScript安卓应用程序中处理安卓生命周期:https://docs.nativescript.org/core-concepts/application-lifecycle#android-activity-events

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

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

使用“上一步”按钮,然后使用“最近”按钮继续...

EN

回答 1

Stack Overflow用户

发布于 2019-07-10 09:44:09

你需要删除销毁事件的监听器。由于您使用android.on来分配事件侦听器,因此还需要使用android.off

您可以找到一个完整的示例herehere。我还更新了你的playground

在您的ngOnInit函数中,我将android.on赋值给一个监听器,例如

代码语言:javascript
复制
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上,我将取消订阅所有的听众。

代码语言:javascript
复制
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向你展示了代码,你也可以给其他事件赋值/取消赋值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56882880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档