---
# System prepended metadata

title: 使用 FCM 建立App推播服務 Web Push Notifications to App(App篇)

---

# 使用 FCM 建立App推播服務 Web Push Notifications to App(App篇)

大家好，我是app組曾經的某一位組長ヽ(✿ﾟ▽ﾟ)ノ，因緣際會下在一次的專案中寫了一點App中FCM的相關功能，因此寫了一篇部落格來記錄，以下內容如有謬誤請不吝賜教_(:3 」∠ )_

前言：自從Google cloud Message(GCM)在2019被移除了之後，Firebase Cloud Messaging（FCM）成為了一種新的跨平台的消息傳遞解決方案。

[詳情可以去看firebase的官方文件](https://firebase.google.com/docs/cloud-messaging/fcm-architecture)

## FCM體系結構概述

- 註冊設備以接收來自FCM的消息 。客戶端應用程序的實例進行註冊以接收消息，從而獲得唯一標識該應用程序實例的註冊令牌。
- 發送和接收下游消息 。
    - 發送消息。應用服務器將消息發送到客戶端應用：
        1. 該消息是在Notifications作曲器或受信任的環境中編寫的，並且消息請求被發送到FCM後端。
        2. FCM後端接收消息請求，生成消息ID和其他元數據，並將其發送到平台特定的傳輸層。
        3. 當設備在線時，消息將通過平台特定的傳輸層發送到設備。
        4. 在設備上，客戶端應用接收消息或通知。
- 總結自官方文件敘述
![](https://i.imgur.com/F1tMOzV.png)

## 一、開始之前

需要符合以下要求：

- 目標API級別16（Jelly Bean）或更高版本
- 使用Gradle 4.1或更高版本
- 使用Jetpack（AndroidX） ，其中包括滿足以下版本要求：
    - com.android.tools.build:gradle v3.2.1或更高版本
    - compileSdkVersion 28或更高版本

## 二、配置環境

- 在Android studio 專案 build.gradle的dependencies中加入這兩行

```java=
implementation 'com.google.firebase:firebase-messaging:20.2.4'
implementation 'com.google.firebase:firebase-analytics:17.5.0' 
```

- 可以在Manifast中這樣設定通知的icon與顏色

```xml=
<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
     notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/colorAccent" />
```

## 三、進入正題

1. 監控token生成
- 目前在身分證中使用的是這個方法

```java=
    @Override
    public void onTokenRefresh() {
        String token = FirebaseInstanceId.getInstance().getToken();
        registerToken(token);
        Log.d("FCM", "Token:"+token);
    }
```

- 當前20.0.4版本有支援新方法

```java=
@Override
public void onNewToken(String token) {
    Log.d(TAG, "Refreshed token: " + token);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(token);
}
```

2. 接收推播內容

```java=
@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO your code
    }
```

3. 在重新起動FCM時調用

```java=
FirebaseMessaging.getInstance().setAutoInitEnabled(true);

```







