Expo Notification 教學

cool
10 min readMay 4, 2024

--

本教程主要是分享關於「如何使用 expo-notifications 進行廣播通知」(Android)透過 Expo backend 實現基本的 push notification。

前置准備

步驟

  1. 安裝相關的套件
  2. 編寫代碼
  3. EAS 打包生成專案
  4. 創建 FCM v1 + 設置 EAS Project Credentials
    (Firebase Could Message)
  5. 再重新構建應用

安裝相關的套件

  1. 先安裝 Expo + EAS 指令套件
npm -g install expo-cli eas-cli

2. 生成新專案

npx create-expo-app "expo-notification"
cd expo-notification

3. 安裝 Expo Notification 所需的 library

npx expo install expo-notifications expo-device expo-constants

4. 最後需要 sharp 用於建構項目的依賴

npm i sharp

編寫代碼

簡化後, App.js 文件內容:
也能參考官方

import { useState, useEffect } from 'react';
import { Text, View, Button, TextInput } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';

Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});

async function registerForPushNotificationsAsync() {
let token;

if(Device.isDevice){
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;

// if notification permission not granted, request the permission again
if(existingStatus !== 'granted')
finalStatus = (await Notifications.requestPermissionsAsync()).status;
if(finalStatus !== 'granted'){
alert('Failed to get push token for push notification!');
return;
}

// Learn more about projectId:
// https://docs.expo.dev/push-notifications/push-notifications-setup/#configure-projectid
const projectId =
Constants?.expoConfig?.extra?.eas?.projectId ??
Constants?.easConfig?.projectId;

token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
}
else
alert('Must use physical device for Push Notifications');

return token;
}

async function sendPushNotification({ token, title, body }){
const message = {
to: token,
title, body
};
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message),
};

await fetch('https://exp.host/--/api/v2/push/send', options);
}

export default function App(){
const [expoPushToken, setExpoPushToken] = useState("");
const [inputToken, setInputToken] = useState("");
const [title, setTitle] = useState("A notification title");
const [body, setBody] = useState("📝 Here is the body content...");

useEffect(() => {
registerForPushNotificationsAsync().then(token => {
setExpoPushToken(token);
setInputToken(token);
});
}, []);

return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
<Text>Your expo push token: {expoPushToken}</Text>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
{/* Input: Token */}
<Text>Token: </Text>
<TextInput value={inputToken} onChangeText={new_text => setInputToken(new_text)} />

{/* Input: Title */}
<Text>Title: </Text>
<TextInput value={title} onChangeText={new_text => setTitle(new_text)} />

{/* Input: Body */}
<Text>Body: </Text>
<TextInput value={body} onChangeText={new_text => setBody(new_text)} />
</View>

{/* Button: Push Notification */}
<Button title="Push Notification"
onPress={async() => {
await sendPushNotification({
token: inputToken,
title, body,
});
}}
/>
</View>
);
}

透過 EAS 打包生成專案

在進行打包前,將需要的 permission 加至 app.json

...
"android":{
...
"package": "com.cool.expo.notification",
"permissions": ["RECEIVE_BOOT_COMPLETED", "SCHEDULE_EXACT_ALARM"]
},
...

接下來能透過 eas-cli 指令部署

npx eas build -p android --profile preview

√ Would you like to automatically create an EAS project for @cool.void/expo-notification? ...yes
√ What would you like your Android application id to be? ... com.cool.expo.notification
√ Generate a new Android Keystore? ... yes

application id 是和 app.json 裡 package 一致(application id 避免使用到 Java 保留的關鍵字)

創建 FCM v1 (Firebase Could Message)

  1. 前往 Firebase Console 新建項目
  2. 在你的項目加入授權的 App,並下載 google-services.json 文件
    (在 app.json 追加 google-services.json 路徑,讓構建的 Android App 能使用 Firebase 服務)
授權 App 能使用你的 Firebase

下載 google-services.json 並將文件路徑添加進 app.json

"android":{
...
"googleServicesFile": "./google-services.json"
},

3. 到 Project settings > Service accounts,點擊 Generate New Private Key

private key 用於上傳到 EAS 後台,讓 Expo back-end 可以調用 FCMv1

將下載的 private key 放至 project folder 裡面

npx eas credentials

√ Select platform » Android
√ Which build profile do you want to configure? » preview

? What do you want to do?
> Google Service Account
> Manage your Google Service Account Key for Push Notifications (FCM V1)
> Set up a Google Service Account Key for Push Notifications (FCM V1)
> [Upload a new service account key]

√ Would you like to use this file? ... yes

上傳完畢 Ctrl + C 退出即可

再重新構建應用

使用以下指令再重新構建應用

npx eas build -p android --profile preview

--

--

cool
cool

No responses yet