我正在使用 react-native-notifications -版本2.1.7库在 react-native 移动应用中接收通知。我不想设置与通知相关的侦听器,直到用户提供了接收通知的权限。
Q1。该文档说,强烈建议将侦听器注册保持在全局范围而不是屏幕范围。 如果我在要求用户提供权限的屏幕上设置侦听器,我会遇到什么问题?
第二季度。如果设备令牌侦听器NotificationsAndroid.setRegistrationTokenUpdateListener()
位于promise中,则似乎无法正常工作。 我在这里缺少什么?,请在下面查看我的代码。
// 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()
答案 0 :(得分:1)
似乎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);
});