首页 > 解决方案 > 验证权限后才设置监听器

问题描述

我正在使用react-native-notifications - 版本 2.1.7 库在react-native移动应用程序中接收通知。在用户提供接收通知的权限之前,我不想设置与通知相关的侦听器。

Q1。该文档说,强烈建议将听众注册保持在全局范围而不是屏幕范围内。如果我在要求用户提供权限的屏幕上设置侦听器,会出现什么问题?

Q2。如果设备令牌侦听NotificationsAndroid.setRegistrationTokenUpdateListener()器在承诺中,它似乎不起作用。我在这里想念什么?请在下面查看我的代码。

// This function is called when the user clicks on the button "Provide permission to receive notifications."
const _requestPermissionNotification = async () => {
    let hasPermission = false; 
    try {
        hasPermission = await NotificationsAndroid.isRegisteredForRemoteNotifications();
    }
    catch (error) {
        Alert.alert(
            "Notification", 
            "To utilise the full functionality of this app, Permission to receive notifications is required.", 
            [{ text: "Ok." }] 
        );
    } // end of: try/catch 

    if (hasPermission) {
        // A. Register Token 
        // THIS LISTENER DOES NOT SEEM TO WORK UNLESS IT IS SET UP OUTSIDE THE COMPONENT! 
        NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => {
            console.log("PermissionsScreen - setRegistrationTokenUpdateListener - deviceToken:", deviceToken);
        });
        // B. Pending Notifications
        PendingNotifications.getInitialNotification()
            .then((notification) => {
                console.log("PermissionsScreen - getInitialNotification - notification:", notification);
            })
            .catch((err) => console.error("getInitialNotifiation failed", err));
        // C. Notification Opened
        NotificationsAndroid.setNotificationOpenedListener((notification) => {
            console.log("PermissionsScreen - setNotificationOpenedListener - :data", notification.getData());
        });
        // D.a Notification Received 
        NotificationsAndroid.setNotificationReceivedListener((notification) => {
            console.log("PermissionsScreen - setNotificationReceivedListener - data:", notification.getData());
        });
        // D.b Notification Received "IN FOREGROUND"
        NotificationsAndroid.setNotificationReceivedInForegroundListener((notification) => {
            console.log("PermissionsScreen - setNotificationReceivedInForegroundListener (foreground)", notification.getData());
        });
    } // end of: if()
}; // end of: _requestPermissionNotification()

标签: react-nativereact-native-android

解决方案


React-Native-Notifications 3.1.1 版似乎不再有这些限制。

以下代码使用了新命令,可以在 Promise 和组件中使用。

// Step A.1: Register this app to receive notifications.
Notifications.registerRemoteNotifications(); 

// Step A.2: Get the device token 
Notifications.events().registerRemoteNotificationsRegistered( (event) => { 
    console.log("deviceToken:", event.deviceToken);
});

推荐阅读