To set up Firebase Cloud Messaging (FCM) for notifications in a React Expo Android project, you'll need to follow these steps:
Install necessary packages:
bashCopyexpo install expo-notifications
expo install expo-device
expo install @react-native-firebase/app
expo install @react-native-firebase/messaging
Set up a Firebase project and download the google-services.json file.
Place the google-services.json file in your project's root directory.
Modify your app.json to include FCM configuration:
jsonCopy{
"expo": {
...
"android": {
...
"googleServicesFile": "./google-services.json",
"package": "your.package.name"
}
}
}
Initialize Firebase in your app:
javascriptCopyimport { initializeApp } from '@react-native-firebase/app';
import messaging from '@react-native-firebase/messaging';
// Initialize Firebase
initializeApp();
Request notification permissions:
javascriptCopyimport { Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
} else {
alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
return token;
}
Set up a listener for incoming messages:
javascriptCopyimport messaging from '@react-native-firebase/messaging';
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('A new FCM message arrived!', JSON.stringify(remoteMessage));
// Handle the message here
});
return unsubscribe;
}, []);
Handle background messages:
javascriptCopymessaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
To send the FCM token to your server:
javascriptCopyasync function sendFCMTokenToServer(token) {
// Implement your server communication logic here
console.log('Sending FCM token to server:', token);
}
useEffect(() => {
registerForPushNotificationsAsync().then(token => sendFCMTokenToServer(token));
}, []);