我正在使用 notifee 在 React Native 应用程序中创建通知。我注意到,默认情况下,通知会被 android 阻止(请参阅“设置”->“应用”->“我的应用”)。我必须在我的应用程序中的某个地方设置权限吗?
当我在应用程序设置中启用通知时,它们工作正常,但我希望在安装 apk 时启用它们。
是的,如果您的目标是 Android 13,则必须明确请求通知权限。
在 AndroidManifest.xml 中粘贴以下行:
<uses-permission android:name="android.permission.POST_NOTIFICATION"/>
然后在您的应用程序中:
import { PermissionsAndroid } from 'react-native'
const requestNotificationPermission = async () => {
try {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATION
)
} catch (err) {
if (_DEV_) console.warn('requestNotificationPermission error: ', err)
}
}
权限可以命名为“POST_NOTIFICATION”或“POST_NOTIFICATIONS”,具体取决于您的 RN 版本。
在android中不需要显式请求通知权限,甚至
POST_NOTIFICATION
也被弃用了,
在 android 中,默认情况下启用通知,直到 & 除非你强行关闭,为了一个简单的解决方案,
当您使用 notifee 时,我建议您使用
你的父组件/App.js 组件中的 requestPermission 函数
useEffect(() => {
(async () => {
// ask for notification permission
await notifee.requestPermission();
})();
return () => {
// this now gets called when the component unmounts
};
}, []);