我遇到一个问题,本地通知在 Android 中不显示,但在 IOS 中显示。我已经创建了权限和电池优化检查,看看这是否是问题所在。通知确实会发出声音,并在左上角显示一个小方块,如果我单击并拖动,则会显示本地通知。我现在正在使用模拟器,并且已经在真实设备上尝试过。
这就是我调用通知的方式。
<Button
title="Trigger Push Notification"
size="large"
onPress={() => onDisplayNotification('default', 'Default Channel', 'Spotback
Android', 'Local push notification')}
/>
这是 Notifee 组件。
import notifee, { AndroidStyle, AuthorizationStatus, Notification } from '@notifee/react-native';
import { Alert } from 'react-native';
export const onDisplayNotification = async (id, name, title, body, smallIcon?) => {
// Request permissions (required for iOS)
await notifee.requestPermission();
const settings = await notifee.getNotificationSettings();
const batteryOptimizationEnabled = await notifee.isBatteryOptimizationEnabled();
if (batteryOptimizationEnabled) {
// 2. ask your users to disable the feature
Alert.alert(
'Restrictions Detected',
'To ensure notifications are delivered, please disable battery optimization for the app.',
[
// 3. launch intent to navigate the user to the appropriate screen
{
text: 'OK, open settings',
onPress: async () => await notifee.openBatteryOptimizationSettings(),
},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
],
{ cancelable: false }
);
}
if (settings.authorizationStatus == AuthorizationStatus.AUTHORIZED) {
console.log('Notification permissions has been authorized');
} else if (settings.authorizationStatus == AuthorizationStatus.DENIED) {
console.log('Notification permissions has been denied');
}
// }
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id,
name,
});
await notifee.displayNotification({
title,
body,
android: {
channelId,
smallIcon,
pressAction: {
id,
},
},
});
};
请将您的频道 ID(默认)和频道名称(默认频道)更改为其他内容,例如: id: 自定义频道 名称:自定义频道
尝试像这样创建频道:
const channelId = await notifee.createChannel({
...,
importance: AndroidImportance.HIGH, //Add this line.
});
来自文档:
https://notifee.app/react-native/docs/android/appearance
应用于频道/通知的最高重要性级别。通知将显示在应用程序顶部,允许直接交互,而无需拉下通知栏。此级别仅适用于需要立即关注的紧急通知,例如来电、消息等。
import notifee, { AndroidImportance } from '@notifee/react-native';
const channelId = await notifee.createChannel({
id: 'important',
name: 'Important Notifications',
importance: AndroidImportance.HIGH,
});
await notifee.displayNotification({
title: 'Your account requires attention',
body: 'You are overdue payment on one or more of your accounts!',
android: {
channelId,
importance: AndroidImportance.HIGH,
},
});