向後台應用程式發送測試訊息

要開始使用 FCM,請建立最簡單的用例:當應用程式位於裝置後台時,從通知編輯器向開發設備發送測試通知訊息。此頁面列出了實現此目的的所有步驟,從設定到驗證 - 如果您已為 FCM設定了 Android 用戶端應用程序,它可能會涵蓋您已經完成的步驟。

設定SDK

如果您已經為您的應用程式啟用了其他 Firebase 功能,本部分將介紹您可能已完成的任務。

在你開始之前

  • 安裝或更新Android Studio到最新版本。

  • 確保您的專案符合以下要求:

    • 目標 API 等級 19 (KitKat) 或更高
    • 使用Android 4.4或更高版本
    • 使用Jetpack (AndroidX) ,其中包括滿足以下版本要求:
      • com.android.tools.build:gradle v7.3.0 或更高版本
      • compileSdkVersion 28或更高版本
  • 設定實體設備或使用模擬器來運行您的應用程式。
    請注意,依賴 Google Play 服務的 Firebase SDK要求裝置或模擬器安裝 Google Play 服務。

  • 使用您的 Google 帳戶登入 Firebase

如果您還沒有 Android 項目,只是想嘗試 Firebase 產品,則可以下載我們的快速入門範例之一。

創建 Firebase 項目

在將 Firebase 新增至 Android 應用程式之前,您需要建立一個 Firebase 專案來連接到您的 Android 應用程式。請造訪了解 Firebase 專案以了解有關 Firebase 專案的更多資訊。

向 Firebase 註冊您的應用

要在 Android 應用程式中使用 Firebase,您需要向 Firebase 專案註冊您的應用程式。註冊您的應用程式通常稱為將您的應用程式「新增」到您的專案中。

  1. 轉到Firebase 控制台

  2. 在專案概述頁面的中心,按一下Android圖示 ( ) 或新增應用程式以啟動設定工作流程。

  3. Android 套件名稱欄位中輸入應用程式的套件名稱。

  4. (可選)輸入其他應用程式資訊:應用程式暱稱偵錯簽章憑證 SHA-1

  5. 點擊註冊應用程式

新增 Firebase 設定檔

  1. 下載 Firebase Android 設定檔 ( google-services.json ) 並將其新增至您的應用程式:

    1. 點擊下載 google-services.json以取得您的 Firebase Android 設定檔。

    2. 將設定檔移到應用程式的模組(應用程式層級)根目錄中。

  2. 要讓 Firebase SDK 可以存取google-services.json設定檔中的值,您需要Google services Gradle 外掛程式( google-services )。

    1. 根級(專案級) Gradle 檔案( <project>/build.gradle.kts<project>/build.gradle )中,新增 Google 服務外掛程式作為依賴項:

      Kotlin

      plugins {
        id("com.android.application") version "7.3.0" apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id("com.google.gms.google-services") version "4.4.1" apply false
      }
      

      Groovy

      plugins {
        id 'com.android.application' version '7.3.0' apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id 'com.google.gms.google-services' version '4.4.1' apply false
      }
      
    2. 模組(應用程式層級) Gradle 檔案(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle )中,新增 Google 服務外掛程式:

      Kotlin

      plugins {
        id("com.android.application")
      
        // Add the Google services Gradle plugin
        id("com.google.gms.google-services")
        // ...
      }
      

      Groovy

      plugins {
        id 'com.android.application'
      
        // Add the Google services Gradle plugin
        id 'com.google.gms.google-services'
        // ...
      }
      

將 Firebase SDK 新增到您的應用

  1. 模組(應用程式層級)Gradle 檔案(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle )中,新增 Firebase Cloud 的依賴項Android 訊息傳遞庫。我們建議使用Firebase Android BoM來控制函式庫版本控制。

    為了獲得 Firebase Cloud Messaging 的最佳體驗,我們建議在您的 Firebase 專案中啟用 Google Analytics ,並將適用於 Google Analytics 的 Firebase SDK 新增至您的應用程式。

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.4"))
    
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-messaging")
        implementation("com.google.firebase:firebase-analytics")
    }
    

    透過使用Firebase Android BoM ,您的應用程式將始終使用 Firebase Android 程式庫的相容版本。

    (替代方法)在不使用 BoM 的情況下新增 Firebase 庫依賴項

    如果您選擇不使用 Firebase BoM,則必須在其依賴項行中指定每個 Firebase 庫版本。

    請注意,如果您在應用程式中使用多個Firebase 程式庫,我們強烈建議使用 BoM 來管理程式庫版本,這可確保所有版本相容。

    dependencies {
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-messaging:23.4.1")
        implementation("com.google.firebase:firebase-analytics:21.5.1")
    }
    
    正在尋找 Kotlin 特定的庫模組?2023 年 10 月(Firebase BoM 32.5.0)開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。

  2. 將您的 Android 專案與 Gradle 檔案同步。

訪問註冊令牌

若要將訊息傳送到特定設備,您需要知道該設備的註冊令牌。由於您需要在通知控制台的欄位中輸入令牌才能完成本教學課程,因此請確保在檢索令牌後複製令牌或安全地儲存它。

在應用程式首次啟動時,FCM SDK 會為客戶端應用程式實例產生註冊令牌。如果您想要定位單一裝置或建立裝置群組,則需要透過擴充FirebaseMessagingService並覆蓋onNewToken來存取此令牌。

本節介紹如何檢索令牌以及如何監視令牌的變更。由於令牌在首次啟動後可能會輪換,因此強烈建議您檢索最新更新的註冊令牌。

註冊令牌可能會在以下情況下變更:

  • 該應用程式已在新設備上恢復
  • 用戶卸載/重新安裝應用程式
  • 用戶清除應用程式資料。

檢索目前註冊令牌

當您需要檢索目前令牌時,請呼叫FirebaseMessaging.getInstance().getToken()

Kotlin+KTX

FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
    if (!task.isSuccessful) {
        Log.w(TAG, "Fetching FCM registration token failed", task.exception)
        return@OnCompleteListener
    }

    // Get new FCM registration token
    val token = task.result

    // Log and toast
    val msg = getString(R.string.msg_token_fmt, token)
    Log.d(TAG, msg)
    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
})

Java

FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
          if (!task.isSuccessful()) {
            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
            return;
          }

          // Get new FCM registration token
          String token = task.getResult();

          // Log and toast
          String msg = getString(R.string.msg_token_fmt, token);
          Log.d(TAG, msg);
          Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

監控代幣生成

每當產生新令牌時,就會觸發onNewToken回呼。

Kotlin+KTX

/**
 * Called if the FCM registration token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the
 * FCM registration token is initially generated so this is where you would retrieve the token.
 */
override fun onNewToken(token: String) {
    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
    // FCM registration token to your app server.
    sendRegistrationToServer(token)
}

Java

/**
 * There are two scenarios when onNewToken is called:
 * 1) When a new token is generated on initial app startup
 * 2) Whenever an existing token is changed
 * Under #2, there are three scenarios when the existing token is changed:
 * A) App is restored to a new device
 * B) User uninstalls/reinstalls the app
 * C) User clears app data
 */
@Override
public void onNewToken(@NonNull 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
    // FCM registration token to your app server.
    sendRegistrationToServer(token);
}

獲得令牌後,您可以將其發送到您的應用程式伺服器並使用您喜歡的方法儲存它。

發送測試通知訊息

  1. 在目標裝置上安裝並執行應用程式。在 Apple 裝置上,您需要接受接收遠端通知的權限請求。

  2. 確保該應用程式位於裝置的背景。

  3. 在 Firebase 控制台中,開啟訊息傳遞頁面

  4. 如果這是您的第一個訊息,請選擇建立您的第一個行銷活動

    1. 選擇Firebase 通知訊息,然後選擇建立
  5. 否則,在「行銷活動」標籤上,選擇「新行銷活動」 ,然後選擇「通知」

  6. 輸入訊息文字。所有其他欄位都是可選的。

  7. 從右側窗格中選擇傳送測試訊息

  8. 在標記為 新增 FCM 註冊令牌 的欄位中,輸入您在本指南上一部分中獲得的註冊令牌。

  9. 選擇測試

選擇“測試”後,目標用戶端裝置(應用程式位於背景)應該會收到通知。

若要深入了解向您的應用程式發送的訊息,請參閱FCM 報告儀表板,該儀表板記錄Apple 和Android 裝置上發送和開啟的訊息數,以及Android 應用程式的「展示次數」(使用者看到的通知)數據。

下一步

向前台應用程式發送訊息

當您的應用程式在背景時成功發送通知訊息後,請參閱在 Android 應用程式中接收訊息以開始傳送到前台應用程式。

超越通知訊息

若要超越通知訊息並向您的應用程式添加其他更高級的行為,請參閱: