1.安装
yarn add @react-native-firebase/messaging
yarn add react-native-push-notification
yarn add @react-native-community/push-notification-ios
2.android 设置
1.android/build.gradle
buildscript {
ext {
googlePlayServicesVersion = "16.0.1"
googlePlayServicesVisionVersion = "16.2.0"
googlePlayServicesAuthVersion = "19.2.0"
}
repositories {
}
dependencies {
classpath 'com.google.gms:google-services:4.4.0' // <--- firebase
}
}
2.android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
3.android/app/build.gradle
apply plugin: 'com.google.gms.google-services'
dependencies {
implementation project(':react-native-push-notification')
implementation 'com.google.firebase:firebase-analytics:21.0.0'
implementation 'com.google.android.gms:play-services-auth:21.0.0'
}
4.android/settings.gradle
include ':react-native-notifications' //添加
project(':react-native-notifications').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-notifications/lib/android/app') //添加
3.代码
1.入口文件 index.js
import PushNotification, { Importance } from "react-native-push-notification";
// 创建渠道id
PushNotification.createChannel(
{
channelId: "Power-bank-news", // (required)
channelName: "Power-bank-news", // (required)
channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
playSound: false, // (optional) default: true
soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
},
(created) => console.log(`通知渠道是否创建,true 创建成功,false 已创建 '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);
2.路由文件 route.js
import messaging from '@react-native-firebase/messaging'
import PushNotification from 'react-native-push-notification'
import PushNotificationIOS from '@react-native-community/push-notification-ios';
async componentDidMount() {
this.messagingSub = await messaging().onMessage(remoteMessage => {
if (Platform.OS === 'ios') {
PushNotificationIOS.addNotificationRequest({
id: String(num++),
body: remoteMessage.notification.body,
title: remoteMessage.notification.title,
userInfo: {}
});
} else {
PushNotification.localNotification({
channelId: 'Power-bank-news',
// id: 0,
title: remoteMessage.notification.title, // (optional)
message: remoteMessage.notification.body, // (required)
})
}
});
}
4.下载firebase 中的google-services.json文件
1.把文件放置在android/app下