react-native - 验证权限后才设置监听器
问题描述
我正在使用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-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);
});
推荐阅读
- javascript - id 没有从 nodejs 中的链接保存
- spring-boot - Get Response When It is Ready In Spring Boot
- windows - 未找到内核驱动程序
- java - 我无法在 Java 中以长数据类型打印出 Math 类的结果?
- yii2 - 在基本项目 yii2 的 dektrium 模块 rbac 中创建规则类
- python - 更快的方法来阈值 4-D numpy 数组
- scrollview - 滚动视图 SwiftUI
- oauth - 无法创建具有全局范围的 zoho oauth 客户端 ID
- reactjs - 从按钮中删除事件
- reactjs - React Apollo 在突变后更新客户端缓存