# Firebase FCM
在 Android 上設置 Firebase 雲消息傳遞客戶端應用

* FCM 格式
notification messages (2KB)
data messages (4KB)
https://console.firebase.google.com/u/0/project/
google-services.json
* 使用ChromeRestClient 推撥 FCM
ARC ChromeRestClient
https://github.com/jarrodek/ChromeRestClient
https://install.advancedrestclient.com/install
* FCM
https://firebase.google.com/docs/cloud-messaging/send-message
---
處理訊息的方法
didReceiveRemoteNotification() on iOS
onMessageReceived() on Android
---
* Notification messages (json 格式)
```typescript
{
"to" : "cOjgBhS9NjQ:APA91bGhbyHlwlXFQ...",
"notification" :
{
"body" : "內容", // 內容
"title" : "標題" // 標題
}
}
```
* Data messages (json 格式)
```typescript
{
"to" : "cOjgBhS9NjQ:APA91bGhbyHlwlXFQ...",
"data" : {
"url" : "xxxx",
"id" : "xxxx",
"temp" : "xxxx"
}
}
* 兩種訊息同時送
{
"to" : "cOjgBhS9NjQ:APA91bGhbyHlwlXFQ...",
"notification" :
{
"body" : "內容", // 內容
"title" : "標題" // 標題
},
"data" : {
"url" : "xxxx",
"id" : "xxxx",
"temp" : "xxxx"
}
}
---
## 申請 https://console.firebase.google.com
### server_key(伺服器金鑰)
雲端通訊 - Cloud Messaging API - 伺服器金鑰
### app_token(AppToken)
一般設定 - google-services.json - 放在專案內 app資料夾下
---
* Request URL
```typescript
POST https://fcm.googleapis.com/fcm/send
```
* Headers
```typescript
Content-Type: application/json
Authorization: key=server_key
```
* Body
```typescript
{
"to": "app_token",
"data": {
"pushid": "4",
"title": "Good TEST",
"body": "add your message",
"action": "2",
"url": "https://www.facebook.com/"
},
"priority": "high"
}
```
如果應用程式在關閉狀態下收到 Firebase Cloud Messaging (FCM) 的推播,FirebaseMessagingService 將無法收到推播內容。這是因為當應用程式關閉時,FCM 會自動將推播顯示在系統的通知欄中,而不會將推播傳遞到 FirebaseMessagingService。
如果希望在應用程式關閉狀態下仍然能夠處理推播內容,可以使用 FCM 的「數據消息(Data Message)」而不是「通知消息(Notification Message)」。通知消息是由 FCM 自動處理的,它會將推播顯示在通知欄上,但無法確保傳遞到 FirebaseMessagingService。而數據消息則是直接將推播傳遞到 FirebaseMessagingService,讓你有機會在應用程式關閉狀態下處理推播。
以下是一個示例,展示如何使用數據消息:
在 FCM 的推播中,將 data 欄位用於數據消息,而不是使用 notification 欄位。例如:
json
```
{
"to": "<device_token>",
"data": {
"title": "推播標題",
"body": "推播內容"
}
}
```
在你的 FirebaseMessagingService 中,覆寫 onMessageReceived 方法,這個方法將在接收到數據消息時被調用。你可以在這個方法中處理推播內容,無論應用程式是在前台還是後台運行。例如:
```
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
// 從數據消息中獲取推播內容
String title = remoteMessage.getData().get("title");
String body = remoteMessage.getData().get("body");
// 在這裡處理推播內容
}
}
}
```
透過這種方式,無論你的應用程式是在前台還是後台運行,FirebaseMessagingService 都將收到推播內容,並能夠進行適當的處理。
請注意,使用數據消息可能需要更多的開發工作,因為你需要在應用程式中處理和顯示推播內容,而不是依賴 FCM 的預設通知處理。但這將使你能夠更靈活地控制推播的處
Regenerate response
Continue generating
測試
https://testfcm.com/
https://pushtry.com/
ref
http://jasonchiucc.github.io/2016/07/11/firebase-tutorial-cloud-messaging/
https://firebase.google.com/docs/cloud-messaging/fcm-architecture?hl=zh-tw