要開始使用 FCM,請構建最簡單的用例:當應用程序在設備後台運行時,將測試通知消息從通知編輯器發送到開發設備。此頁面列出了實現此目的的所有步驟,從設置到驗證——如果您已經為 FCM設置了 Android 客戶端應用程序,它可能涵蓋您已經完成的步驟。
設置開發工具包
如果您已經為您的應用啟用了其他 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 項目註冊您的應用程序。註冊您的應用程序通常稱為將您的應用程序“添加”到您的項目中。
轉到Firebase 控制台。
在項目概覽頁面的中央,單擊Android圖標 (
) 或添加應用程序以啟動設置工作流程。在Android 程序包名稱字段中輸入您的應用程序的程序包名稱。
包名稱在設備和 Google Play 商店中唯一標識您的應用程序。
包名稱通常稱為應用程序 ID 。
在模塊(應用程序級)Gradle 文件中找到應用程序的包名稱,通常
app/build.gradle
(例如包名稱:com.yourcompany.yourproject
)。請注意,包名稱值區分大小寫,並且在您的 Firebase 項目中註冊後,無法更改此 Firebase Android 應用程序。
(可選)輸入其他應用信息:應用暱稱和調試簽名證書 SHA-1 。
應用暱稱:僅在 Firebase 控制台中對您可見的內部便利標識符
調試簽名證書 SHA-1 :Firebase 身份驗證(使用Google 登錄或電話號碼登錄時)和Firebase 動態鏈接需要SHA-1 哈希。
單擊註冊應用程序。
添加 Firebase 配置文件
下載然後將 Firebase Android 配置文件 (
) 添加到您的應用程序:google-services.json 單擊下載 google-services.json以獲取您的 Firebase Android 配置文件。
將您的配置文件移動到應用程序的模塊(應用程序級)根目錄中。
Firebase 配置文件包含項目的唯一但非機密標識符。要了解有關此配置文件的更多信息,請訪問了解 Firebase 項目。
您可以隨時再次下載您的Firebase 配置文件。
確保配置文件名未附加其他字符,例如
(2)
。
要使
配置文件中的值可供 Firebase SDK 訪問,您需要Google 服務 Gradle 插件(google-services.json google-services
)。在您的根級(項目級) Gradle 文件 (
<project>/build.gradle
) 中,將 Google 服務插件添加為構建腳本依賴項:buildscript { repositories { // Make sure that you have the following two repositories google() // Google's Maven repository mavenCentral() // Maven Central repository } dependencies { ... // Add the dependency for the Google services Gradle plugin classpath 'com.google.gms:google-services:4.3.15' } } allprojects { ... repositories { // Make sure that you have the following two repositories google() // Google's Maven repository mavenCentral() // Maven Central repository } }
在您的模塊(應用程序級別) Gradle 文件(通常是
<project>/<app-module>/build.gradle
)中,添加 Google 服務插件:plugins { id 'com.android.application' // Add the Google services Gradle plugin id 'com.google.gms.google-services' ... }
將 Firebase SDK 添加到您的應用
在您的模塊(應用級)Gradle 文件(通常為
<project>/<app-module>/build.gradle
)中,添加 Firebase Cloud Messaging Android 庫的依賴項。我們建議使用Firebase Android BoM來控制庫版本。為了獲得 Firebase 雲消息傳遞的最佳體驗,我們建議在您的 Firebase 項目中啟用 Google Analytics ,並將適用於 Google Analytics 的 Firebase SDK 添加到您的應用程序中。
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.3') // 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.1.2' implementation 'com.google.firebase:firebase-analytics:21.2.0' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.3') // 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.1.2' implementation 'com.google.firebase:firebase-analytics-ktx:21.2.0' }
將您的 Android 項目與 Gradle 文件同步。
使用 Android Gradle 插件 (AGP) v4.2 或更早版本的 Gradle 構建需要啟用 Java 8 支持。否則,這些 Android 項目在添加 Firebase SDK 時會出現構建失敗。
要修復此構建失敗,您可以遵循以下兩個選項之一:
- 將錯誤消息中列出的
compileOptions
添加到您的應用程序級build.gradle
文件中。 - 將 Android 項目的
minSdkVersion
增加到 26 或更高。
在此常見問題解答中了解有關此構建失敗的更多信息。
- 將錯誤消息中列出的
訪問註冊令牌
要向特定設備發送消息,您需要知道該設備的註冊令牌。由於您需要在通知控制台的字段中輸入令牌才能完成本教程,因此請務必復制令牌或在檢索後安全地存儲它。
在您的應用程序初始啟動時,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); }
獲得令牌後,您可以將其發送到您的應用服務器並使用您喜歡的方法存儲它。
發送測試通知消息
在目標設備上安裝並運行該應用程序。在 Apple 設備上,您需要接受接收遠程通知的許可請求。
確保應用程序在設備的後台運行。
在 Firebase 控制台中,打開消息頁面。
如果這是您的第一條消息,請選擇創建您的第一個營銷活動。
- 選擇Firebase Notification messages並選擇Create 。
否則,在“活動”選項卡上,選擇“新建活動” ,然後選擇“通知” 。
輸入消息文本。所有其他字段都是可選的。
從右窗格中選擇發送測試消息。
在標記為添加 FCM 註冊令牌的字段中,輸入您在本指南上一節中獲得的註冊令牌。
選擇測試。
選擇測試後,目標客戶端設備(應用程序在後台)應該會收到通知。
要深入了解向您的應用程序發送的消息,請參閱FCM 報告儀表板,它記錄了在 Apple 和 Android 設備上發送和打開的消息數量,以及 Android 應用程序的“印象”(用戶看到的通知)數據。
下一步
向前台應用程序發送消息
在您的應用程序處於後台時成功發送通知消息後,請參閱在 Android 應用程序中接收消息以開始向前台應用程序發送消息。
超越通知消息
要超越通知消息並向您的應用程序添加其他更高級的行為,請參閱: