Firebase+NativeScript:点击推送通知后跳转指定页面的问题
解决NativeScript+Firebase后台点击通知无法跳转页面的问题
我之前在做NativeScript结合Firebase的项目时也踩过这个坑,咱们来拆解问题并解决它!
问题根源
你当前的代码里,当应用在后台被通知唤醒时,onMessageReceivedCallback触发的时机早于路由系统的完全初始化,这时候调用routerExtensions.navigate自然不会生效。另外,后台点击通知的场景,Firebase其实有专门的回调来处理,而不是只依赖消息接收回调。
解决方案
我们需要分三种场景处理:应用前台、后台存活、完全被杀死,同时确保路由初始化完成后再执行跳转。修改你的app.component.tns.ts代码如下:
import { Component, OnInit } from "@angular/core"; import { RouterExtensions } from "@nativescript/angular"; import * as firebase from "@nativescript/firebase"; import * as application from "@nativescript/core/application"; @Component({ selector: "app-root", templateUrl: "./app.component.html" }) export class AppComponent implements OnInit { private pendingNotification: any = null; constructor(private routerExtensions: RouterExtensions) {} ngOnInit() { this.initFirebaseNotifications(); this.handleAppLaunchFromNotification(); } private initFirebaseNotifications() { firebase.init({ showNotificationsWhenInForeground: true, // 处理消息接收(仅前台提示用) onMessageReceivedCallback: (message) => { if (message.foreground) { alert('app is open'); } else { // 后台存活时,先暂存消息,等路由就绪再跳转 this.pendingNotification = message; } }, // 专门处理通知点击的核心回调! onNotificationTapCallback: (message) => { // 不管应用状态,点击通知直接跳转 this.routerExtensions.navigate(["messages"], { clearHistory: true // 避免返回闪屏页 }); } }).then(() => { // Firebase初始化完成后,检查是否有暂存的后台通知 if (this.pendingNotification) { this.routerExtensions.navigate(["messages"], { clearHistory: true }); this.pendingNotification = null; } }).catch(err => { console.error("Firebase初始化失败: ", err); }); } private handleAppLaunchFromNotification() { // 处理应用从完全杀死状态被通知唤醒的场景 application.on(application.launchEvent, (args) => { // Android平台处理 if (args.android) { const intent = args.android.intent; if (intent && intent.getExtras()) { const extras = intent.getExtras(); // 判断是否来自Firebase通知 if (extras.containsKey("google.message_id")) { this.routerExtensions.navigate(["messages"], { clearHistory: true }); } } } // iOS平台处理 else if (args.ios) { const launchOptions = args.ios.launchOptions; if (launchOptions && launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) { this.routerExtensions.navigate(["messages"], { clearHistory: true }); } } }); } }
关键说明
onNotificationTapCallback:这是Firebase提供的专门处理通知点击的回调,不管应用处于前台、后台还是被杀死状态,用户点击通知时都会触发,是处理跳转的最优选择。- 应用启动事件监听:当应用完全被杀死后,点击通知启动应用时,
onMessageReceivedCallback不会触发,这时候需要通过launchEvent获取启动参数,判断是否来自通知后执行跳转。 clearHistory: true:跳转时添加这个参数,确保用户点击返回按钮不会回到闪屏页,优化体验。
另外要确认你的messages页面已经在Angular路由模块中正确注册,这样跳转才能生效。
内容的提问来源于stack exchange,提问作者Marco Antonio Bagdal
相关产品推荐
相关产品推荐

