In this guide I have covered setup for android platform only. For iOS please check official doc
1.2.1: In the left side panel of firebase console, click on the gear
icon beside Project Overview
1.2.2: In the Settings page, click on the Cloud Messaging
tab to get Server key
& Sender ID
2.1.1: Give it a name and select Google Android
when prompted for platform
2.1.2: Next use the Server key
& Sender ID
from step 1.2.2
2.1.3: Select React Native
as your target SDK
2.1.4: Get the App ID
yarn add react-native-onesignal
or
npm install --save react-native-onesignal
react-native link react-native-onesignal
3.2.1: Modify android/app/src/main/AndroidManifest.xml
<manifest ...>
...
<!-- Add the following 2 lines -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
...
>
<activity
...
android:launchMode="singleTop"> <!-- Add this attribute to your main activity -->
...
</activity>
...
</application>
</manifest>
3.2.2: Modify android/app/build.gradle
Add the following code to the very top of the file
buildscript {
repositories {
maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
}
dependencies {
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.1, 0.99.99]'
}
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
3.2.3: Make sure compileSdkVersion
and buildToolsVersion
is at least API level 26 or higher in android/build.gradle
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
// ...
}
...
import OneSignal from 'react-native-onesignal'; // Import package from node modules
...
export default class App extends Component {
constructor(properties) {
super(properties);
OneSignal.init("YOUR_ONESIGNAL_APPID");
OneSignal.addEventListener('received', this.onReceived);
OneSignal.addEventListener('opened', this.onOpened);
OneSignal.addEventListener('ids', this.onIds);
OneSignal.configure(); // triggers the ids event
}
componentWillUnmount() {
OneSignal.removeEventListener('received', this.onReceived);
OneSignal.removeEventListener('opened', this.onOpened);
OneSignal.removeEventListener('ids', this.onIds);
}
onReceived(notification) {
console.log("Notification received: ", notification);
}
onOpened(openResult) {
console.log('Message: ', openResult.notification.payload.body);
console.log('Data: ', openResult.notification.payload.additionalData);
console.log('isActive: ', openResult.notification.isAppInFocus);
console.log('openResult: ', openResult);
}
onIds(device) {
console.log('Device info: ', device);
}
}