← 资料库索引 ← 个人博客 原始链接 ↗ 🔍
个人博客

推送通知中的 Registration Token:它是什么、如何获取与更新 原文标题:Registration Token in Push Notifications: What It Is, Getting and Updating

发表时间:2026-03-21采集时间:2026-10-09 10:34:59来源:itsectr.com原文语言:en状态:完整

内容概要总结

本文是 IT Sectr 公司技术博客的一篇科普文章,系统讲解 Firebase Cloud Messaging(FCM)中的 Registration Token(注册令牌)。核心结论:Registration Token 是 FCM 分配给每个应用实例(app instance)的、最长可达 4096 个字符的唯一字符串,用于标识特定设备上的某个应用实例;它由应用 ID、设备 ID 以及设备上的 Google 账号共同决定,采用 Base64 编码的随机字符序列,FCM 用它作为投递地址把通知路由到具体设备。

文章强调 token 可能变化:应用首次启动或清除应用数据后会自动生成,开发者必须订阅 onNewToken 回调;服务端必须存储所有设备的最新 token。文章对比了 token 与其他标识符(Device ID/IMEI 永久、Advertising ID 可重置、Instance ID 为旧机制),给出 token 失效的几种情形(应用被移除、从备份恢复到新设备、向过期 token 发送返回 UNREGISTERED)。在 Android 上自 Firebase SDK 21.0.0 起通过 FirebaseMessaging.getInstance().getToken() 获取(旧版经 FirebaseInstanceId,已废弃);在 iOS 上基于 APNs device token,经 MessagingDelegate 的 messaging:didReceiveRegistrationToken 传递。此外给出服务端存储策略(建议保留 token 历史以便回退)、错误处理表与常见问答。

翻译内容

原文内容(English)

⚠ 说明:为与原文结构对齐,已将 20 处小标题还原为 Markdown 标题(层级与 content_en 一致),并补回顶部图片占位符。

作者:IT Sectr

发布于:2026-03-21

阅读时长:8 分钟

Registration Token 是 FCM 用来标识特定设备上某个应用实例的字符串。

该 token 在应用首次启动时或清除应用数据后自动生成。

FCM 使用该 token 把推送通知路由到正确的设备。

token 可能变化——应用必须通过 onNewToken 订阅其更新。

要发送通知,服务端必须存储所有设备的当前 token。

什么是 Registration Token

Registration Token 是 Firebase Cloud Messaging 分配给每个应用实例的唯一字符串,最长可达 4096 个字符。该 token 基于应用 ID、设备 ID 以及设备上的 Google 账号形成。

Token 的结构与用途

Registration Token 由以 Base64 格式编码的随机字符序列组成。FCM 将该 token 用作投递地址——服务端把通知发送到该 token,FCM 再将其路由到特定设备。没有 token,就无法把推送通知寻址到特定用户。

与其他标识符的区别

Registration Token 不应与 Device ID(IMEI)或 Advertising ID 混淆。Device ID 是设备的硬件标识符,而 Advertising ID 用于广告目的。Registration Token 与「应用 + 设备」的组合绑定,一台设备可以针对不同应用拥有多个 token。

标识符用途可变性
Registration TokenFCM 推送通知投递可能变化
Device ID (IMEI)硬件识别永久
Advertising ID定向广告可重置
Instance ID旧版 Firebase 机制删除时改变

何时 token 被视为无效

FCM 可能在多种情况下认为一个 Registration Token 无效。如果应用从设备上被移除,token 会自动吊销。在新设备上从备份恢复数据时,旧的 token 会停止工作。向一个过期的 token 发送通知时,Firebase 也会返回 UNREGISTERED 状态。

FCM 如何分配 Registration Token

Firebase Cloud Messaging 在应用首次启动并调用 getToken() 方法时生成 Registration Token。该过程包括验证 Google Play Services 凭据,并在 Firebase 基础设施中注册该应用。

设备注册流程

当一台设备首次运行集成了 FCM SDK 的应用时,会发生以下过程。Firebase SDK 检查设备上是否存在 Google Play Services。随后 SDK 向 Firebase 服务器发送请求,传递应用 ID 和设备信息。Firebase 服务器创建一个新 token 并将其返回给应用。

FCM 内部机制

FCM 采用基于长连接的架构。在收到 Registration Token 后,设备通过 Android 上的 STOMP 协议或 iOS 上的 APNs 通道,与 Firebase 服务器建立一条持久连接。当服务端把通知发送到该 token 时,FCM 通过该 token 找到设备并投递消息载荷。

Token 重新生成的条件

在以下情况下,FCM 可能重新生成 Registration Token。当在新设备上从备份恢复应用时。删除并重装应用时。通过系统设置清除应用数据时。在设备上登录另一个 Google 账号时。Firebase 建议始终处理 onNewToken 回调以跟踪变化。

在 Android 上获取 Registration Token

在 Android 上,Registration Token 通过 Firebase Messaging SDK 获取。不同 SDK 版本的过程不同——较新的版本使用 FirebaseInstallations API,而非已废弃的 FirebaseInstanceId。

通过 FirebaseInstallations 的现代方式

从 Firebase SDK 21.0.0 版本开始,getToken() 方法通过 FirebaseMessaging 调用。这种方式会自动管理 token 生命周期并订阅其更新。

class MyFirebaseMessagingService : FirebaseMessagingService() {
 override fun onNewToken(token: String) {
 sendRegistrationToServer(token)
 }
 private fun sendRegistrationToServer(token: String) {
 // Sending token to server
 Log.d("FCM", "New token: $token")
 }
 init {
 FirebaseMessaging.getInstance()
 .getToken()
 .addOnCompleteListener { task ->
 if (!task.isSuccessful) {
 Log.w("FCM", "Fetching FCM token failed")
 return@addOnCompleteListener
 }
 val token = task.result
 sendRegistrationToServer(token)
 }
 }
}

在 Activity 或 ViewModel 中处理 token

在某些场景下,token 不是在 Service 中而是直接在 Activity 或 ViewModel 中需要。此时可以在应用生命周期的合适时机调用 getToken()。重要的是,不要在不处理异步的情况下从主线程调用该方法。

class MainActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 getFCMToken()
 }
 private fun getFCMToken() {
 FirebaseMessaging.getInstance().getToken()
 .addOnCompleteListener { task ->
 if (task.isSuccessful) {
 val token = task.result
 Log.d("FCM", "Token: $token")
 }
 }
 }
}

旧版 FirebaseInstanceId 方式

在较旧版本的 Firebase SDK 中(20.x 版本之前),token 通过 FirebaseInstanceId.getInstance().getToken() 获取。该方法已被标记为废弃,不建议在新项目中使用。维护旧代码的开发者应迁移到 FirebaseInstallations API。

在 iOS 上获取 Registration Token

在 iOS 上,获取 Registration Token 的过程在架构上不同——FCM 通过 Apple Push Notification service(APNs)工作。Firebase SDK 从 APNs 接收一个唯一的 device token,将其转换为 FCM 格式,并传递给应用。

APNs 配置与 token 获取

要在 iOS 上使用 FCM,你必须在 Firebase 控制台中配置 APNs 证书或密钥。应用必须通过 UNUserNotificationCenter 请求通知权限。在收到 APNs token 后,Firebase SDK 会自动生成 Registration Token。

import FirebaseMessaging
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate {
 func application(
 application: UIApplication,
 didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey: Any]?
 ) -> Bool {
 FirebaseApp.configure()
 Messaging.messaging().delegate = self
 requestNotificationAuthorization()
 return true
 }
 private func requestNotificationAuthorization() {
 let center = UNUserNotificationCenter.current()
 center.requestAuthorization(options: [.alert, .sound, .badge])
 }
}
extension AppDelegate: MessagingDelegate {
 func messaging(
 messaging: Messaging,
 didReceiveRegistrationToken fcmToken: String?
 ) {
 Log.d("FCM", "Token: \(fcmToken ?? "")")
 sendTokenToServer(token: fcmToken)
 }
}

iOS 与 Android token 的区别

iOS 上的 Registration Token 相比 Android token 更短,因为它基于 APNs device token。当 APNs token 变化时(例如从备份恢复设备或重装应用时发生),Firebase SDK 会自动更新 FCM token。

更新与管理 Registration Token

管理 Registration Token 的生命周期对于可靠地投递推送通知至关重要。如果服务端存储了过期的 token,通知将无法投递,Firebase 会返回 UNREGISTERED 错误。

监控 token 变化

Firebase SDK 提供两种跟踪 token 变化的机制。在 Android 上,使用 FirebaseMessagingService 中的 onNewToken 回调。在 iOS 上,使用 messaging:didReceiveRegistrationToken 委托。两者都会在 token 每次更新时被调用。

// Saving token to SharedPreferences and sending to server
class TokenManager(private val context: Context) {
 companion object {
 private const val PREFS_TOKEN_KEY="fcm_re...oken"
 }
 fun saveToken(token: String) {
 val prefs = PreferenceManager
 .getDefaultSharedPreferences(context)
 prefs.edit().putString(PREFS_TOKEN_KEY, token).apply()
 }
 fun getSavedToken(): String? {
 val prefs = PreferenceManager
 .getDefaultSharedPreferences(context)
 return prefs.getString(PREFS_TOKEN_KEY, null)
 }
}

服务端 token 存储策略

服务端必须把 Registration Token 与用户标识符关联存储。当 token 更新时,客户端把新 token 发送到服务端,服务端替换旧的 token。建议保留 token 历史:如果向新 token 投递失败,可以尝试旧 token。

处理 token 时的错误处理

Firebase 可能在多种情况下返回 token 获取错误。如果设备上缺少 Google Play Services,将无法获取 token。如果超过对 FCM 的请求配额,应实现指数退避进行重试。如果 token 过期,SDK 会自动请求一个新的。

情形结果开发者操作
应用被移除token 被吊销从数据库中删除 token
备份恢复新 token在数据库中更新
Google Play Services 重置token 重新生成处理 onNewToken
token 过期自动更新

常见问题

请检查设备上 Google Play Services 是否可用,验证 google-services.json 文件,并检查 Firebase SDK 版本。确保应用具有联网权限。

token 可能在卸载并重装应用、清除数据、从备份恢复或登录另一个 Google 账号时变化。没有固定的时间间隔。

是的,设备上的每个应用会收到各自的 FCM token。如果一台设备上有三个使用 Firebase 的应用,每个都会有自己唯一的 Registration Token。

通过 Firebase 控制台或 FCM HTTP API 发送一条测试通知。如果 token 无效,API 会返回 UNREGISTERED 或 NOT_FOUND 错误。

Registration Token 不是密钥,但它的泄露会允许向用户设备发送通知。请将 token 存储在安全的数据库中,并使用 HTTPS 进行传输。

Registration Token 是通过 Firebase Cloud Messaging 投递推送通知所必需的元素。

该 token 在首次启动带有 FCM SDK 的应用时自动生成。

在 Android 上,token 通过 FirebaseMessaging.getInstance().getToken() 获取。

在 iOS 上,token 基于 APNs device token,并通过 MessagingDelegate 传递。

token 可能变化——应用必须处理 onNewToken 回调。

服务端必须存储当前 token,并在出现 UNREGISTERED 错误时删除过期的 token。

为可靠投递,请实现 token 变化监控和失败重试机制。

我们将为您交钥匙式开发移动应用

IT Sectr 自 2017 年起为初创企业和企业开发 iOS 与 Android 应用。我们将为您提供建议并提出最佳方案。

FCM——它是什么,Firebase Cloud Messaging 在移动开发中如何工作 →

Device Token:它在 iOS 开发中如何工作、如何获取与管理 →

推送通知中的 Topic 订阅——它是什么、如何工作与设置 →

开发中的功能蔓延(Feature creep)——它是什么、成因及如何应对 →

开发中的垃圾代码(Trash Code)——它是什么、迹象与如何清理 →

Registration Token in Push Notifications: What It Is, How to Get and Update

Author:
IT Sectr

Published:
2026-03-21

Reading time:
8 min

  • Registration Token is a string that identifies an app instance on a specific device for FCM.
  • The token is generated automatically on first launch or after clearing app data.
  • FCM uses the token to route push notifications to the correct device.
  • The token may change — the app must subscribe to updates via onNewToken.
  • To send notifications, the server must store current tokens for all devices.

What Is a Registration Token

Registration Token is a unique string up to 4096 characters long that Firebase Cloud Messaging assigns to each app instance. The token is formed based on the application ID, device ID, and the Google account on the device.

Token Structure and Purpose

A Registration Token consists of a random sequence of characters encoded in Base64 format. FCM uses this token as a delivery address — the server sends a notification to the token, and FCM routes it to the specific device. Without a token, it is impossible to address a push notification to a specific user.

Differences from Other Identifiers

A Registration Token should not be confused with a Device ID (IMEI) or Advertising ID. Device ID is a hardware identifier of the device, while Advertising ID is used for advertising purposes. Registration Token is tied to the combination of app and device, and one device can have multiple tokens for different apps.

IdentifierPurposeMutability
Registration TokenFCM push notification deliveryMay change
Device ID (IMEI)Hardware identificationPermanent
Advertising IDTargeted advertisingCan be reset
Instance IDLegacy Firebase mechanismChanged on deletion

When a Token Is Considered Invalid

FCM may consider a Registration Token invalid in several situations. If the app is removed from the device, the token is automatically revoked. When restoring data from a backup on a new device, the old token stops working. Firebase also returns a UNREGISTERED status when attempting to send a notification to an outdated token.

How FCM Assigns a Registration Token

Firebase Cloud Messaging generates a Registration Token when the app is first launched and the getToken() method is called. The process includes verifying Google Play Services credentials and registering the app in the Firebase infrastructure.

Device Registration Process

When a device runs an app with the integrated FCM SDK for the first time, the following occurs. The Firebase SDK checks for Google Play Services on the device. The SDK then sends a request to Firebase servers, passing the application ID and device information. The Firebase server creates a new token and returns it to the app.

FCM Internal Mechanics

FCM uses an architecture based on long-lived connections. After receiving a Registration Token, the device establishes a persistent connection to Firebase servers via the STOMP protocol on Android or the APNs channel on iOS. When the server sends a notification to the token, FCM finds the device by the token and delivers the payload.

Token Regeneration Conditions

A Registration Token may be regenerated by FCM in the following cases. When restoring an app from a backup on a new device. When deleting and reinstalling the app. When clearing app data through system settings. When signing into a different Google account on the device. Firebase recommends always handling the onNewToken callback to track changes.

Getting a Registration Token on Android

On Android, the Registration Token is obtained through the Firebase Messaging SDK. The process differs for different SDK versions — newer versions use the FirebaseInstallations API instead of the deprecated FirebaseInstanceId.

Modern Approach via FirebaseInstallations

Starting with Firebase SDK version 21.0.0, the getToken() method is called through FirebaseMessaging. This approach automatically manages the token lifecycle and subscribes to its updates.

class MyFirebaseMessagingService : FirebaseMessagingService() {
 override fun onNewToken(token: String) {
 sendRegistrationToServer(token)
 }
 private fun sendRegistrationToServer(token: String) {
 // Sending token to server
 Log.d("FCM", "New token: $token")
 }
 init {
 FirebaseMessaging.getInstance()
 .getToken()
 .addOnCompleteListener { task ->
 if (!task.isSuccessful) {
 Log.w("FCM", "Fetching FCM token failed")
 return@addOnCompleteListener
 }
 val token = task.result
 sendRegistrationToServer(token)
 }
 }
}

Handling the Token in Activity or ViewModel

In some scenarios, the token is needed not in the service but directly in an Activity or ViewModel. In this case, getToken() can be called at a convenient point in the app lifecycle. It is important not to call this method from the main thread without handling asynchrony.

class MainActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 getFCMToken()
 }
 private fun getFCMToken() {
 FirebaseMessaging.getInstance().getToken()
 .addOnCompleteListener { task ->
 if (task.isSuccessful) {
 val token = task.result
 Log.d("FCM", "Token: $token")
 }
 }
 }
}

Legacy FirebaseInstanceId Method

In older versions of the Firebase SDK (before version 20.x), the token was obtained via FirebaseInstanceId.getInstance().getToken(). This method is marked as deprecated and is not recommended for use in new projects. Developers maintaining legacy code should migrate to the FirebaseInstallations API.

Getting a Registration Token on iOS

On iOS, the process of obtaining a Registration Token differs architecturally — FCM works through the Apple Push Notification service (APNs). The Firebase SDK receives a unique device token from APNs, converts it to FCM format, and passes it to the app.

APNs Setup and Token Retrieval

To use FCM on iOS, you must configure an APNs certificate or key in the Firebase console. The app must request notification permission via UNUserNotificationCenter. After receiving the APNs token, the Firebase SDK automatically generates the Registration Token.

import FirebaseMessaging
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate {
 func application(
 application: UIApplication,
 didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey: Any]?
 ) -> Bool {
 FirebaseApp.configure()
 Messaging.messaging().delegate = self
 requestNotificationAuthorization()
 return true
 }
 private func requestNotificationAuthorization() {
 let center = UNUserNotificationCenter.current()
 center.requestAuthorization(options: [.alert, .sound, .badge])
 }
}
extension AppDelegate: MessagingDelegate {
 func messaging(
 messaging: Messaging,
 didReceiveRegistrationToken fcmToken: String?
 ) {
 Log.d("FCM", "Token: \(fcmToken ?? "")")
 sendTokenToServer(token: fcmToken)
 }
}

Differences Between iOS and Android Tokens

The Registration Token on iOS is smaller compared to the Android token, as it is based on the APNs device token. The Firebase SDK automatically updates the FCM token when the APNs token changes, which happens when restoring a device from a backup or reinstalling the app.

Updating and Managing Registration Tokens

Managing the lifecycle of a Registration Token is critically important for reliable push notification delivery. If the server stores an outdated token, notifications will not be delivered, and Firebase will return a UNREGISTERED error.

Monitoring Token Changes

The Firebase SDK provides two mechanisms for tracking token changes. On Android, the onNewToken callback in FirebaseMessagingService is used. On iOS, the messaging:didReceiveRegistrationToken delegate is used. Both are called each time the token is updated.

// Saving token to SharedPreferences and sending to server
class TokenManager(private val context: Context) {
 companion object {
 private const val PREFS_TOKEN_KEY = "fcm_registration_token"
 }
 fun saveToken(token: String) {
 val prefs = PreferenceManager
 .getDefaultSharedPreferences(context)
 prefs.edit().putString(PREFS_TOKEN_KEY, token).apply()
 }
 fun getSavedToken(): String? {
 val prefs = PreferenceManager
 .getDefaultSharedPreferences(context)
 return prefs.getString(PREFS_TOKEN_KEY, null)
 }
}

Server-Side Token Storage Strategy

The server must store the Registration Token in association with the user identifier. When the token is updated, the client sends the new token to the server, and the server replaces the old one. It is recommended to keep a token history: if a notification is not delivered to the new token, the old one can be tried.

Error Handling When Working with Tokens

Firebase may return a token retrieval error in several cases. If Google Play Services are missing on the device, the token will not be obtained. If the request quota to FCM is exceeded, an exponential backoff should be implemented for retries. If the token expires, the SDK automatically requests a new one.

SituationResultDeveloper Action
App removalToken is revokedDelete token from database
Backup restorationNew tokenUpdate in database
Google Play Services resetToken regeneratedHandle onNewToken
Token expirationAutomatic update

Frequently Asked Questions

Check that Google Play Services is available on the device, verify the google-services.json file, and check the Firebase SDK version. Make sure the app has internet permission.

The token may change when uninstalling and reinstalling the app, clearing data, restoring from a backup, or signing into a different Google account. There is no fixed time interval.

Yes, each app on the device receives its own FCM token. If a device has three apps with Firebase, each will have its own unique Registration Token.

Send a test notification through the Firebase console or the FCM HTTP API. If the token is invalid, the API will return a UNREGISTERED or NOT_FOUND error.

A Registration Token is not a secret key, but its leak allows sending notifications to the user's device. Store tokens in a secure database and use HTTPS for transmission.

  • Registration Token is a required element for delivering push notifications via Firebase Cloud Messaging.
  • The token is generated automatically on first launch of an app with the FCM SDK.
  • On Android, the token is obtained via FirebaseMessaging.getInstance().getToken().
  • On iOS, the token is based on the APNs device token and is passed via the MessagingDelegate.
  • The token may change — the app must handle the onNewToken callback.
  • The server must store current tokens and delete outdated ones when an UNREGISTERED error occurs.
  • For reliable delivery, implement token change monitoring and a retry mechanism for failures.

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

FCM — what it is, how Firebase Cloud Messaging works in mobile development
→

Device Token: How It Works, Obtaining and Managing in iOS Development
→

Topic Subscription in Push Notifications — What It Is, How It Works, and Setup
→

Feature creep in development — what it is, causes and how to fight it
→

Trash Code in Development — What It Is, Signs, and How to Clean Up
→

放大预览