iT邦幫忙

2024 iThome 鐵人賽

DAY 16
0

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));
}, []);


上一篇
[Day 15] React Expo push token 無法取得問題
下一篇
[Day 17] 在 Firebase 開立專案
系列文
跨平台協同:在 React Native 和 Kotlin 應用中實現無縫交互 -以 Notification 為例30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言