Catch up on highlights from Firebase at Google I/O 2023. Learn more

向後台應用發送測試消息

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

設置SDK

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

在你開始之前

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

  • 確保您的項目滿足以下要求:

    • 目標 API 級別 19 (KitKat) 或更高
    • 使用Android 4.4或更高版本
    • 使用Jetpack (AndroidX) ,其中包括滿足以下版本要求:
      • com.android.tools.build:gradle v3.2.1 或更高版本
      • 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.2.0" apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id("com.google.gms.google-services") version "4.3.15" apply false
      }
      

      Groovy

      plugins {
        id 'com.android.application' version '7.2.0' apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id 'com.google.gms.google-services' version '4.3.15' 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 添加到您的應用中。

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
    
        // 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-ktx")
        implementation("com.google.firebase:firebase-analytics-ktx")
    }
    

    通過使用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-ktx:23.2.1")
        implementation("com.google.firebase:firebase-analytics-ktx:21.3.0")
    }
    

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
    
        // 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.2.1")
        implementation("com.google.firebase:firebase-analytics:21.3.0")
    }
    

  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 應用程序中接收消息以開始發送到前台應用程序。

超越通知消息

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