---
# System prepended metadata

title: FCM Cloud Messaging
tags: [GDSC]

---


# FCM Cloud Messaging

> Firebase 提供的應用程式通知工具 FKT

![](https://hackmd.io/_uploads/SyjpZPxKh.png)

----

## 可應用通知平台

既然是通知，想必是應用在使用者的環境

- Android
- IOS
- Unity
- Web
- Flutter

----

## 通知流程架構 BaaS

![](https://hackmd.io/_uploads/rJQM7vxF3.png)

---

## 實作環節 

----

### 被通知者 Flutter 為例

放置 Firebase Service 設定檔案
![](https://hackmd.io/_uploads/r1KdLNZth.png)


----

```dart=
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();//初始化 Firebase Core
  messaging = FirebaseMessaging.instance; //取得 FCM 物件
  final fcmToken = await messaging.getToken();
  //設置使用者 Token 用於發布
  print(fcmToken);
  // 也可以透過訂閱主題 發布給訂閱者
  await messaging.subscribeToTopic('flutter_notification');
  // 套用 Firebase 初始化監聽器
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}
```

----

### 發布者以 Python 為例

![](https://hackmd.io/_uploads/SJ1p8EZY2.png)


----

```python=
import firebase_admin
import os
from firebase_admin import credentials
from firebase_admin import messaging
# 從 Firebase Console 下載
cred = credentials.Certificate('petmonitoringsystem-729da-firebase-adminsdk-85ae8-e6dd9c9252.json')
firebase_admin.initialize_app(cred)

message = messaging.Message(
    notification=messaging.Notification(
        title='FCM Notification',
        body='This is a test notification from FCM'
    ),
    token=os.getenv("FCM_DEVICE_TOKEN")#剛剛 Flutter 取得的使用者 Token
)

response = messaging.send(message)
print('Successfully sent message:', response)
```

---

![](https://hackmd.io/_uploads/ByglfYJc2.png)


----

## 謝謝大家


