← 资料库索引 ← 官方文档 原始链接 ↗ 🔍
官方文档

管理 Firebase 安装与 ID 原文标题:Manage Firebase installations and IDs  |  Firebase Documentation

发表时间:(页面未标注)采集时间:2026-10-09 10:34:46来源:firebase.google.com原文语言:en状态:完整

内容概要总结

本文是 Firebase 官方文档「管理 Firebase 安装与 ID」,介绍 Firebase 安装服务(FIS)及其为每个已安装的 Firebase 应用实例分配的 Firebase 安装 ID(FID)。文档首先列出内部使用 FID 的 Firebase 服务(Cloud Messaging、Crashlytics、In-App Messaging、Performance Monitoring、Remote Config、ML、User Segmentation Storage)及各自用途;随后说明何时需要直接调用 FIS API(删除安装及其数据、获取标识符以定位特定安装、获取安装认证令牌),并给出 iOS/Android/JavaScript/Flutter 各平台的 SDK 添加方式与代码。文档详述:删除安装时绑定数据在 180 天内从各服务在线与备份系统移除;客户端 API 与服务端 API 两种删除方式及其差异;FID 对每个应用的每次安装都不同,同一设备上不同应用拥有不同 FID;安装认证令牌为 JWT 格式、默认有效期一周且不可撤销;以及卸载重装、清缓存、后台不活跃(当前阈值 270 天)会导致 FID 删除或轮换,并提供监听方式;最后给出从 Instance ID 迁移到 Firebase 安装的方法与最低 SDK 版本表。

翻译内容

原文内容(English)

⚠ 说明:(结构对齐:按原文补回 75 个标题(含各代码标签)与文首图片占位符 [[IMG:0]]。)
Firebase
Firebase

管理 Firebase 安装与 ID

借助「集合」保持井然有序。保存并分类内容,依据你的偏好。

Firebase 安装服务(FIS)为每个已安装的 Firebase 应用实例提供一个 Firebase 安装 ID(FID)。Firebase 安装 ID 被以下 Firebase 服务内部使用:

Firebase 服务Firebase 安装功能
Firebase Cloud MessagingFirebase Cloud Messaging 使用 Firebase 安装 ID 来定位设备以进行消息投递。
Firebase CrashlyticsFirebase Crashlytics 会根据应用实例的 Firebase 安装 ID 的变化来轮换 Crashlytics 安装 UUID。未来,安装 ID 可能被用于启用增强崩溃报告和崩溃管理服务的功能。
Firebase In-App MessagingFirebase In-App Messaging 使用 Firebase 安装 ID 来定位设备以进行消息投递。
Firebase Performance MonitoringPerformance Monitoring 使用 Firebase 安装 ID 来计算访问网络资源的唯一 Firebase 安装数量,以确保访问模式足够匿名。它还将 Firebase 安装 ID 与 Firebase Remote Config 结合使用,以管理性能事件上报的速率。
Firebase Remote ConfigRemote Config 使用 Firebase 安装 ID 来选择返回给终端设备的配置值。Remote Config 的个性化功能使用 Firebase 安装 ID 将应用事件数据与 Firebase 安装关联起来,以预测并向终端设备返回最优配置值。
Firebase ML被称为 installation auth token(安装认证令牌)的凭证被 Firebase ML 用于在与应用实例交互时进行设备认证,例如向应用实例分发开发者模型。
Firebase User Segmentation StorageFirebase User Segmentation Storage 存储 Firebase 安装 ID 及相关属性和分群,以向使用它们的其他 Firebase 服务提供定位信息。

通常,Firebase 服务使用 Firebase 安装服务时不需要开发者直接与 FIS API 交互。然而,有些情况下应用开发者可能希望直接调用 FIS API,例如:

  • 删除某个 Firebase 安装以及与该安装绑定的数据。
  • 获取标识符(Firebase 安装 ID)以便定位特定的应用安装。
  • 获取安装认证令牌以对 Firebase 安装进行认证。

要开始直接调用 FIS API,请将 SDK 添加到你的应用。

将 Firebase 安装 SDK 添加到你的应用

iOS+

将 Firebase 安装的依赖添加到你的 Podfile:

pod 'FirebaseInstallations'

运行 pod install 并打开创建的 .xcworkspace 文件。

在你的 UIApplicationDelegate 中导入 FirebaseCore 模块,以及你的应用委托所使用的任何其他 Firebase 模块。例如,要使用 Cloud Firestore 和 Authentication:

SwiftUI

import SwiftUI
import FirebaseCore
import FirebaseFirestore
import FirebaseAuth
// ...

Swift

import FirebaseCore
import FirebaseFirestore
import FirebaseAuth
// ...

Objective-C

@import FirebaseCore;
@import FirebaseFirestore;
@import FirebaseAuth;
// ...

在你的应用委托的 application(_:didFinishLaunchingWithOptions:) 方法中配置一个 FirebaseApp 共享实例:

SwiftUI

// Use Firebase library to configure APIs
FirebaseApp.configure()

Swift

// Use Firebase library to configure APIs
FirebaseApp.configure()

Objective-C

// Use Firebase library to configure APIs
[FIRApp configure];

如果你使用 SwiftUI,你必须创建一个应用委托并通过 UIApplicationDelegateAdaptor 或 NSApplicationDelegateAdaptor 将其附加到你的 App 结构体。你还必须禁用应用委托 swizzling。更多信息请参阅 SwiftUI 说明。

SwiftUI

@main
struct YourApp: App {
 // register app delegate for Firebase setup
 @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
 var body: some Scene {
 WindowGroup {
 NavigationView {
 ContentView()
 }
 }
 }
}

Android

将 Firebase 安装 Android SDK 的依赖添加到你的模块(应用级)Gradle 文件(通常为 app/build.gradle):

implementation 'com.google.firebase:firebase-installations:19.1.2'

JavaScript

取决于你的 Web 应用如何托管,你的配置可能被自动处理,或者你可能需要更新 Firebase 配置对象。

例如,如果你的依赖添加到 index.html 中,则在 <head> 元素中添加该依赖:

<script src="/__/firebase/13.0.0/firebase-installations.js"></script>

Flutter

在你的 Flutter 项目根目录下,运行以下命令来安装 Firebase 安装插件:

flutter pub add firebase_app_installations

flutter run

导入 Firebase 安装插件:

import 'package:firebase_app_installations/firebase_app_installations.dart';

删除 Firebase 安装

与 Firebase 安装绑定的数据通常不具有个人身份识别性。不过,给用户一个管理和删除此数据的选项仍然是有帮助的。

Firebase 安装 ID 对每个应用的每次安装都不同;同一设备上的不同应用拥有不同的 Firebase 安装 ID。Firebase 安装 ID 用于标识应用安装以及绑定到这些应用安装的数据。

当你删除一个安装 ID 时,绑定到该安装 ID 的数据会在 180 天内从所有使用 Firebase 安装 ID 来标识安装的 Firebase 服务的在线和备份系统中移除。该过程在 Google 关于删除与保留的声明中有高层次的描述。

除非你在应用中禁用所有生成 FID 的服务,否则 FIS 会在几天内创建一个新的 ID。Firebase 将新创建的 ID 视为一个新的 Firebase 安装,并且不以任何方式将其与之前的 ID 或数据关联。

通过客户端 API 调用删除 FID

要删除由 Firebase 服务生成的 FID,请从 Firebase 安装 SDK 调用相应方法:

Swift

do {
 try await Installations.installations().delete()
 print("Installation deleted");
} catch {
 print("Error deleting installation: \(error)")
}

Objective-C

[[FIRInstallations installations] deleteWithCompletion:^(NSError *error) {
 if (error != nil) {
 NSLog(@"Error deleting Installation %@", error);
 return;
 }
 NSLog(@"Installation deleted");
}];

Java

FirebaseInstallations.getInstance().delete()
 .addOnCompleteListener(new OnCompleteListener<Void>() {
 @Override
 public void onComplete(@NonNull Task<Void> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation deleted");
 } else {
 Log.e("Installations", "Unable to delete Installation");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().delete().addOnCompleteListener { task ->
 if (task.isComplete) {
 Log.d("Installations", "Installation deleted")
 } else {
 Log.e("Installations", "Unable to delete Installation")
 }
}

JavaScript

await firebase.installations().delete();

Dart

await FirebaseInstallations.instance.delete();

通过服务端 API 调用删除 FID

要通过服务端 API 调用删除 FID,请先将 Firebase Admin SDK 添加到你的服务器(如果尚未添加)。

添加 SDK 后,通过用你选择的语言调用删除函数来删除 FID(注意:除 Node.js 外,这些方法反映的是 Instance ID 命名。不过,当用任何当前 Firebase SDK 调用时,它们实际上都会删除 FID)。

Node.js

// An FIDsent from a client service SDK
const idToDelete = 'eyJhbG...iIs5';
admin.installations().deleteInstallation(idToDelete);

Java

// An FID sent from a client service SDK
String idToDelete = "eyJhbG...iIs5";
FirebaseInstanceId.getInstance().deleteInstanceIdAsync(idToDelete).get();

Python

from firebase_admin import instance_id
 # An FID sent from a client service SDK
 id_to_delete = 'eyJhbG...iIs5'
 instance_id.delete_instance_id(id_to_delete)

Go

client, err := app.InstanceId(ctx)
if err != nil {
 log.Fatalln("error initializing client", err)
}
iidToDelete := "eyJhbG...iIs5"
if err := client.DeleteInstanceId(ctx, iidToDelete); err != nil {
 log.Fatalln("error deleting FID", err)
}

当你通过服务端 API 调用删除一个 Firebase 安装 ID 时,Firebase 服务会启动删除绑定到该安装 ID 的数据的过程,在 1-2 天的过程中停止接受该 ID 的新数据,然后通知客户端应用该 ID 已被删除。在 Firebase 通知客户端应用之前,该应用的某些服务可能仍会定位到该 ID——例如,一个 Firebase 安装可能仍会在几个小时内继续收到 FCM 通知。

如果你想删除当前的 Firebase 安装 ID 并立即用一个全新的、无关的 ID 使用 Firebase 服务,请使用客户端 API 来处理删除。

获取客户端标识符

如果你需要标识你应用的特定安装,可以通过获取 Firebase 安装 ID 来实现。例如,为了创建用于 BigQuery 导入的应用安装分群,或在 Firebase In-App Messaging 开发期间进行测试,你可以使用相应的 Firebase 安装 ID 来标识和定位正确的设备。

要获取 Firebase 安装 ID:

Swift

do {
 let id = try await Installations.installations().installationID()
 print("Installation ID: \(id)")
} catch {
 print("Error fetching id: \(error)")
}

Objective-C

[[FIRInstallations installations] installationIDWithCompletion:^(NSString *identifier, NSError *error) {
 if (error != nil) {
 NSLog(@"Error fetching Installation ID %@", error);
 return;
 }
 NSLog(@"Installation ID: %@", identifier);
}];

Java

FirebaseInstallations.getInstance().getId()
 .addOnCompleteListener(new OnCompleteListener<String>() {
 @Override
 public void onComplete(@NonNull Task<String> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation ID: " + task.getResult());
 } else {
 Log.e("Installations", "Unable to get Installation ID");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().id.addOnCompleteListener { task ->
 if (task.isSuccessful) {
 Log.d("Installations", "Installation ID: " + task.result)
 } else {
 Log.e("Installations", "Unable to get Installation ID")
 }
}

JavaScript

const installationId = await firebase.installations().getId();
console.log(installationId);

Dart

String id = await FirebaseInstallations.instance.getId();

获取安装认证令牌

Firebase 服务可以使用从 FIS 获取的认证令牌来对 Firebase 安装进行认证。例如,在为 Remote Config 设计 A/B 测试时,你可以使用安装认证令牌来认证一个被定位的测试设备。

安装认证令牌是一个短期的 bearer 令牌,采用 JSON web token(JWT)格式,包含某个安装的以下信息:

  • Firebase 安装 ID
  • 关联的项目(projectNumber)
  • 关联的 Firebase 应用 ID(appId)
  • 该令牌的过期日期

安装认证令牌无法被撤销,并在其过期日期前一直有效。默认令牌有效期为一周。

要获取安装认证令牌:

Swift

do {
 let result = try await Installations.installations()
 .authTokenForcingRefresh(true)
 print("Installation auth token: \(result.authToken)")
} catch {
 print("Error fetching token: \(error)")
}

Objective-C

[[FIRInstallations installations] authTokenForcingRefresh:true
 completion:^(FIRInstallationsAuthTokenResult *result, NSError *error) {
 if (error != nil) {
 NSLog(@"Error fetching Installation token %@", error);
 return;
 }
 NSLog(@"Installation auth token: %@", [result authToken]);
}];

Java

FirebaseInstallations.getInstance().getToken(/* forceRefresh */true)
 .addOnCompleteListener(new OnCompleteListener<InstallationTokenResult>() {
 @Override
 public void onComplete(@NonNull Task<InstallationTokenResult> task) {
 if (task.isSuccessful() && task.getResult() != null) {
 Log.d("Installations", "Installation auth token: " + task.getResult().getToken());
 } else {
 Log.e("Installations", "Unable to get Installation auth token");
 }
 }
});

Kotlin

val forceRefresh = true
FirebaseInstallations.getInstance().getToken(forceRefresh)
 .addOnCompleteListener { task ->
 if (task.isSuccessful) {
 Log.d("Installations", "Installation auth token: " + task.result?.token)
 } else {
 Log.e("Installations", "Unable to get Installation auth token")
 }
 }

JavaScript

const installationToken = await firebase.installations()
 .getToken(/* forceRefresh */ true);
console.log(installationToken);

Dart

String token = await FirebaseInstallations.instance.getToken();

监控 Firebase 安装 ID 的生命周期

在应用的正常运营过程中,Firebase 安装 ID(FID)不需要特别监控。但是,显式获取并使用 FID 的应用应当添加逻辑来监控 FID 潜在的删除或轮换。以下是 FID 可能被删除或轮换的一些情形:

  • 应用的卸载或重新安装,例如终端用户在新设备上安装。
  • 终端用户清除应用或设备的缓存。
  • 由于应用不活跃而在后端触发 FID 删除(当前该阈值为不活跃 270 天)。

当应用在这类情形下经历 FID 轮换或删除时,它们会被分配一个新的 FID。此外,与已删除 FID 关联的安装认证令牌会被删除,无论其自身的成熟度如何,并被替换为新的安装认证令牌。

应用可以监控这些变化并相应地作出响应。

Swift

installationIDObserver = NotificationCenter.default.addObserver(
 forName: .InstallationIDDidChange,
 object: nil,
 queue: nil
) { (notification) in
 // Fetch new Installation ID
 Task {
 await self.fetchInstallationToken()
 }
}

Objective-C

__weak __auto_type weakSelf = self;
self.installationIDObserver = [[NSNotificationCenter defaultCenter]
 addObserverForName: FIRInstallationIDDidChangeNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull notification) {
 // Fetch new Installation ID
 [weakSelf fetchInstallationsID];
}];

每当分配新的 FID 时,会向默认的 NSNotificationCenter 发送一个名为 NSNotificationName.InstallationIDDidChange 的 NSNotification。

Android

Kotlin 和 Java 客户端应添加重试逻辑,以应对获取新 FID 的失败调用。

JavaScript

Web 应用可以订阅 onIdChange 钩子。

每当创建新的 FID 时,会触发订阅的回调:

await firebase.installations().onIdChange((newId) => {
 console.log(newId);
 // TODO: Handle new installation ID.
});

Dart

FirebaseInstallations.instance.onIdChange.listen((token) {
 print('FID token: $token');
});

从 Instance ID 迁移到 Firebase 安装

在引入 Firebase 安装之前,Firebase 依赖 Instance ID SDK 来作为应用安装的标识符。Firebase 安装在可靠性、性能和安全性方面相比 Instance ID 具有显著优势。依赖 Instance ID SDK 的 Firebase 应用应迁移到 Firebase 安装。

迁移过程因你的应用而异:

  • 不直接调用 Instance ID API 的应用,可以通过更新其 SDK 版本来迁移。大多数 Firebase 应用属于此类。
  • 显式对 Instance ID 进行 API 调用的应用,必须更新 SDK 版本并修改代码,用 Firebase 安装或 FCM 的等效方法替换 Instance ID 方法。如果你的应用使用 Instance ID 来获取 FCM 注册令牌,或显式使用 Instance ID 来定位应用实例或用于任何其他目的,你将需要更新你的应用代码。

目前,FIS 与旧标识符 Firebase Instance ID 向后兼容。删除 IID 是使用以下 Firebase SDK 请求数据删除的另一种方法:

  • 早于 2020 年 2 月 27 日的 Android SDK

这意味着应用并非必须迁移到 Firebase 安装;不过,强烈建议这样做。

升级到 Firebase 安装所需的最低 SDK 版本

要从 Instance ID 迁移到 Firebase 安装,请确保你的应用至少使用以下 Firebase SDK 所列的最低版本号:

Firebase SDK最低 Android 版本最低 iOS 版本
Firebase Cloud Messagingv20.3.0v6.34.0
Remote Configv19.2.0v6.24.0
Google Analytics for Firebase(Measurement SDK)v17.4.4v6.18.0
In-App Messagingv19.0.7v6.24.0
Performance Monitoringv19.0.8v6.21.0
Crashlyticsv17.2.1v6.23.0
ML Kitv22.1.2v6.28.0

更新显式调用 Instance ID API 的代码

如果你的 Android 或 Apple 应用直接使用 Instance ID SDK 方法,你可以用 Firebase 安装 SDK 或 FCM SDK 中的完全相同的替代方法来替换该用法。

获取标识符

获取 Instance ID 的方法被替换为获取安装 ID 的方法。例如:

Swift

Messaging.messaging().token { token, error in
 if let error = error {
 print("Error fetching remote FCM registration token: \(error)")
 } else if let token = token {
 print("Remote instance ID token: \(token)")
 }
}

Objective-C

[[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
 if (error != nil) {
 NSLog(@"Error fetching the remote FCM registration token: %@", error);
 } else {
 NSLog(@"Remote FCM registration token: %@", token);
 NSString* message =
 [NSString stringWithFormat:@"FCM registration token: %@", token];
 // display message
 NSLog(@"%@", message);
 }
}];

Java

FirebaseInstanceId.getInstance().getInstanceId()
 .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
 @Override
 public void onComplete(@NonNull Task<InstanceIdResult> task) {
 Log.d("IID_TOKEN", task.getResult().getToken());
 }
 });

Kotlin

FirebaseInstanceId.getInstance().instanceId
 .addOnSuccessListener { result ->
 Log.d("IID_TOKEN", result.token)
 }

Swift

do {
 let id = try await Installations.installations().installationID()
 print("Installation ID: \(id)")
} catch {
 print("Error fetching id: \(error)")
}

Objective-C

[[FIRInstallations installations] installationIDWithCompletion:^(NSString *identifier, NSError *error) {
 if (error != nil) {
 NSLog(@"Error fetching Installation ID %@", error);
 return;
 }
 NSLog(@"Installation ID: %@", identifier);
}];

Java

FirebaseInstallations.getInstance().getId()
 .addOnCompleteListener(new OnCompleteListener<String>() {
 @Override
 public void onComplete(@NonNull Task<String> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation ID: " + task.getResult());
 } else {
 Log.e("Installations", "Unable to get Installation ID");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().id.addOnCompleteListener { task ->
 if (task.isSuccessful) {
 Log.d("Installations", "Installation ID: " + task.result)
 } else {
 Log.e("Installations", "Unable to get Installation ID")
 }
}

删除标识符

删除 Instance ID 的方法被替换为删除 Firebase 安装 ID 的方法。例如:

Swift

InstanceID.instanceID().deleteID { error in
 if let error = error {
 print("Error deleting instance ID: \(error)")
 }
}

Objective-C

[FIRInstanceID instanceID] deleteIDWithHandler:^(NSError *error) {
 if error != nil {
 NSLog(@"Error deleting instance ID: %@", error);
 }
}];

Android

FirebaseInstanceId.deleteInstanceId();

Swift

func delete(completion: @escaping (Error?) -> Void)

Objective-C

- (void)deleteWithCompletion:(nonnull void (^)(NSError *_Nullable))completion;

Java

FirebaseInstallations.getInstance().delete()
 .addOnCompleteListener(new OnCompleteListener<Void>() {
 @Override
 public void onComplete(@NonNull Task<Void> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation deleted");
 } else {
 Log.e("Installations", "Unable to delete Installation");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().delete().addOnCompleteListener { task ->
 if (task.isComplete) {
 Log.d("Installations", "Installation deleted")
 } else {
 Log.e("Installations", "Unable to delete Installation")
 }
}

获取 FCM 注册令牌

在引入 Firebase Installations 之前,FCM 客户端从 Instance ID 获取注册令牌。现在,FCM SDK 提供了获取注册令牌的方法。

Java

FirebaseInstanceId.getInstance().getInstanceId()
 .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
 @Override
 public void onComplete(@NonNull Task<InstanceIdResult> task) {
 if (!task.isSuccessful()) {
 Log.w(TAG, "getInstanceId failed", task.getException());
 return;
 }
 // Get new Instance ID token
 String token = task.getResult().getToken();
 // 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();
 }
 });

Kotlin

FirebaseInstanceId.getInstance().instanceId
 .addOnCompleteListener(OnCompleteListener { task ->
 if (!task.isSuccessful) {
 Log.w(TAG, "getInstanceId failed", task.exception)
 return@OnCompleteListener
 }
 // Get new Instance ID token
 val token = task.result?.token
 // Log and toast
 val msg = getString(R.string.msg_token_fmt, token)
 Log.d(TAG, msg)
 Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
 })

Swift

InstanceID.instanceID().instanceID { result, error in
 if let error = error {
 print("Error fetching instance ID: \(error)")
 } else if let result = result {
 print("Instance ID token: \(result.token)")
 }
}

Objective-C

[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
 NSError * _Nullable error) {
 if (error != nil) {
 NSLog(@"Error fetching instance ID: %@", error);
 } else {
 NSLog(@"Instance ID token: %@", result.token);
 }
}];

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();
 }
 });

Kotlin

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()
})

Swift

Messaging.messaging().token { token, error in
 if let error = error {
 print("Error fetching remote FCM registration token: \(error)")
 } else if let token = token {
 print("Remote instance ID token: \(token)")
 }
}

Objective-C

[[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
 if (error != nil) {
 NSLog(@"Error fetching the remote FCM registration token: %@", error);
 } else {
 NSLog(@"Remote FCM registration token: %@", token);
 NSString* message =
 [NSString stringWithFormat:@"FCM registration token: %@", token];
 // display message
 NSLog(@"%@", message);
 }
}];

除另有说明外,本页内容依据 Creative Commons Attribution 4.0 许可授权,代码示例依据 Apache 2.0 许可授权。详情请参阅 Google Developers 站点政策。Java 是 Oracle 和/或其关联公司的注册商标。

最后更新于 2026-10-07 UTC。

Firebase
Firebase

Manage Firebase installations and IDs

Stay organized with collections

Save and categorize content based on your preferences.

The Firebase installations service (FIS) provides a
Firebase installation ID (FID) for each installed instance
of a Firebase app. The Firebase installation ID is used internally by these Firebase
services:

Firebase serviceFirebase installations functionality
Firebase Cloud Messaging

Firebase Cloud Messaging uses
Firebase installation IDs to target devices for message delivery.

Firebase Crashlytics

Firebase Crashlytics rotates the Crashlytics installation
UUID based on changes to the app instance's Firebase
installation ID. In the future, the
installation ID may be used to enable features that
enhance crash reporting and crash management services.

Firebase In-App Messaging

Firebase In-App Messaging uses
Firebase installation IDs to target devices for message delivery.

Firebase Performance Monitoring

Performance Monitoring uses Firebase installation IDs
to calculate the number of unique Firebase installations that access
network resources, to ensure that access patterns are
sufficiently anonymous. It also uses
Firebase installation IDs with Firebase Remote Config
to manage the rate of performance event reporting.

Firebase Remote Config

Remote Config uses Firebase installation IDs
to select configuration values to return to end-user devices. The
Remote Config personalization feature uses Firebase installation IDs to
associate app event data with Firebase installations in order to
predict and return optimal configuration values to end-user devices.

Firebase ML

Credentials called

installation auth tokens are used by Firebase ML for
device authentication when interacting with app
instances, for example, to distribute developer models to app instances.

Firebase User Segmentation Storage

Firebase User Segmentation Storage stores Firebase installation IDs
and related attributes and segments to provide targeting information
to other Firebase services that use them.

Typically, Firebase services use the Firebase installations service without
requiring developers to interact directly with the FIS API.
However, there are cases where app developers might want to directly call the
FIS API, such as:

  • To delete a Firebase installation and data tied to the installation.
  • To retrieve identifiers (Firebase installation IDs) in order to target

specific app installations.

  • To retrieve installation auth tokens to authenticate Firebase

installations.

To get started with directly calling
the FIS API, add the SDK to your app.

Add the Firebase installations SDK to your app

iOS+

  • Add the dependency for Firebase installations to your Podfile:
pod 'FirebaseInstallations'
  • Run pod install and open the created .xcworkspace file.
  • Import the FirebaseCore module in your UIApplicationDelegate, as well as any other Firebase modules your app delegate uses. For example, to use Cloud Firestore and Authentication:

SwiftUI

import SwiftUI
import FirebaseCore
import FirebaseFirestore
import FirebaseAuth
// ...

Swift

import FirebaseCore
import FirebaseFirestore
import FirebaseAuth
// ...

Objective-C

@import FirebaseCore;
@import FirebaseFirestore;
@import FirebaseAuth;
// ...
  • Configure a FirebaseApp shared instance in your app delegate's application(_:didFinishLaunchingWithOptions:) method:

SwiftUI

// Use Firebase library to configure APIs
FirebaseApp.configure()

Swift

// Use Firebase library to configure APIs
FirebaseApp.configure()

Objective-C

// Use Firebase library to configure APIs
[FIRApp configure];
  • If you're using SwiftUI, you must create an application delegate and attach it to your App struct via UIApplicationDelegateAdaptor or NSApplicationDelegateAdaptor. You must also disable app delegate swizzling. For more information, see the SwiftUI instructions.

SwiftUI

@main
struct YourApp: App {
 // register app delegate for Firebase setup
 @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
 var body: some Scene {
 WindowGroup {
 NavigationView {
 ContentView()
 }
 }
 }
}

Android

Add the dependency for the Firebase installations Android SDK to your
module (app-level) Gradle file (usually app/build.gradle):

implementation 'com.google.firebase:firebase-installations:19.1.2'

JavaScript

Depending on how your web application is hosted, your configuration may be
handled automatically or you may need to update your
Firebase configuration object.

For example, if your dependencies are added in index.html, add the
dependency in the <head> element:

<script src="/__/firebase/13.0.0/firebase-installations.js"></script>

Flutter

From the root directory of your Flutter project, run the following
command to install the Firebase installations plugin:

flutter pub add firebase_app_installations
flutter run

Import the Firebase installations plugin:

import 'package:firebase_app_installations/firebase_app_installations.dart';

Delete a Firebase installation

Data tied to a Firebase installation is generally not personally
identifying. Still, it can be helpful to
give users an option to manage and delete this data.

Firebase installation IDs are different for every installation of every
application; different applications on the same device have different
Firebase installation IDs. Firebase installation IDs identify app
installations and data tied to
those app installations.

When you delete an installation ID, the data tied to that
installation ID is removed from live and backup systems of all
Firebase services that use Firebase installation IDs to identify installations
within 180 days. This process is described at a high level in Google’s
statement on deletion and retention.

Unless you disable all FID-generating services in your
app, FIS creates a new ID within a few days. Firebase
considers the newly-created ID to be a new Firebase installation, and
doesn't associate it with the previous ID or data in any way.

Delete an FID with a client API call

To delete FIDs generated by Firebase services,
call the appropriate method from the Firebase installations SDK:

Swift

do {
 try await Installations.installations().delete()
 print("Installation deleted");
} catch {
 print("Error deleting installation: \(error)")
}

Objective-C

[[FIRInstallations installations] deleteWithCompletion:^(NSError *error) {
 if (error != nil) {
 NSLog(@"Error deleting Installation %@", error);
 return;
 }
 NSLog(@"Installation deleted");
}];

Java

FirebaseInstallations.getInstance().delete()
 .addOnCompleteListener(new OnCompleteListener<Void>() {
 @Override
 public void onComplete(@NonNull Task<Void> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation deleted");
 } else {
 Log.e("Installations", "Unable to delete Installation");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().delete().addOnCompleteListener { task ->
 if (task.isComplete) {
 Log.d("Installations", "Installation deleted")
 } else {
 Log.e("Installations", "Unable to delete Installation")
 }
}

JavaScript

await firebase.installations().delete();

Dart

await FirebaseInstallations.instance.delete();

Delete an FID with a server API call

To delete an FID with a server API
call, add the Firebase Admin SDK to your server, if you haven't already.

Once the SDK is added, delete FIDs through a call to the
deletion function in your language of choice (note: Except for Node.js, these
methods reflect Instance ID naming. However, they all actually delete the
FID when called with any current Firebase SDK).

Node.js

// An FIDsent from a client service SDK
const idToDelete = 'eyJhbGciOiJFUzI1N_iIs5';
admin.installations().deleteInstallation(idToDelete);

Java

// An FID sent from a client service SDK
String idToDelete = "eyJhbGciOiJFUzI1N_iIs5";
FirebaseInstanceId.getInstance().deleteInstanceIdAsync(idToDelete).get();

Python

from firebase_admin import instance_id
 # An FID sent from a client service SDK
 id_to_delete = 'eyJhbGciOiJFUzI1N_iIs5'
 instance_id.delete_instance_id(id_to_delete)

Go

client, err := app.InstanceId(ctx)
if err != nil {
 log.Fatalln("error initializing client", err)
}
iidToDelete := "eyJhbGciOiJFUzI1N_iIs5"
if err := client.DeleteInstanceId(ctx, iidToDelete); err != nil {
 log.Fatalln("error deleting FID", err)
}

When you delete an Firebase installation ID with a server API call, Firebase
services start the process to delete the data tied to that installation ID, stop
accepting new data for that ID over the course of 1-2 days, and then notify the
client app that the ID was deleted. Until Firebase notifies the client app, some
of the app's services might still target the ID—for example, a Firebase
installation might continue to receive FCM notifications for a few
hours.

If you want to delete the current Firebase installation ID and immediately use
Firebase services with a new, unrelated ID, use the client API
to handle the deletion.

Retrieve client identifiers

If you have a requirement to identify particular installations of your app, you
can do so by retrieving the Firebase installation ID. For example, to create
segments of app installs for BiqQuery import, or to perform
testing during Firebase In-App Messaging development, you can identify and
target the correct devices using the corresponding Firebase installation IDs.

To retrieve a Firebase installation ID:

Swift

do {
 let id = try await Installations.installations().installationID()
 print("Installation ID: \(id)")
} catch {
 print("Error fetching id: \(error)")
}

Objective-C

[[FIRInstallations installations] installationIDWithCompletion:^(NSString *identifier, NSError *error) {
 if (error != nil) {
 NSLog(@"Error fetching Installation ID %@", error);
 return;
 }
 NSLog(@"Installation ID: %@", identifier);
}];

Java

FirebaseInstallations.getInstance().getId()
 .addOnCompleteListener(new OnCompleteListener<String>() {
 @Override
 public void onComplete(@NonNull Task<String> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation ID: " + task.getResult());
 } else {
 Log.e("Installations", "Unable to get Installation ID");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().id.addOnCompleteListener { task ->
 if (task.isSuccessful) {
 Log.d("Installations", "Installation ID: " + task.result)
 } else {
 Log.e("Installations", "Unable to get Installation ID")
 }
}

JavaScript

const installationId = await firebase.installations().getId();
console.log(installationId);

Dart

String id = await FirebaseInstallations.instance.getId();

Retrieve installation auth tokens

Firebase services can authenticate Firebase installations with auth tokens
retrieved from FIS. For example, when designing A/B tests
for Remote Config, you can authenticate a targeted test device using
an installation auth token.

An installation auth token is a short-lived bearer token
in JSON web token (JWT) format containing the following information for
an installation:

  • The Firebase installation ID
  • The associated project (projectNumber)
  • The associated Firebase application ID (appId)
  • The token's expiration date

An installation auth token cannot be revoked, and remains valid until
its expiration date. The default token lifetime is one week.

To retrieve an installation auth token:

Swift

do {
 let result = try await Installations.installations()
 .authTokenForcingRefresh(true)
 print("Installation auth token: \(result.authToken)")
} catch {
 print("Error fetching token: \(error)")
}

Objective-C

[[FIRInstallations installations] authTokenForcingRefresh:true
 completion:^(FIRInstallationsAuthTokenResult *result, NSError *error) {
 if (error != nil) {
 NSLog(@"Error fetching Installation token %@", error);
 return;
 }
 NSLog(@"Installation auth token: %@", [result authToken]);
}];

Java

FirebaseInstallations.getInstance().getToken(/* forceRefresh */true)
 .addOnCompleteListener(new OnCompleteListener<InstallationTokenResult>() {
 @Override
 public void onComplete(@NonNull Task<InstallationTokenResult> task) {
 if (task.isSuccessful() && task.getResult() != null) {
 Log.d("Installations", "Installation auth token: " + task.getResult().getToken());
 } else {
 Log.e("Installations", "Unable to get Installation auth token");
 }
 }
});

Kotlin

val forceRefresh = true
FirebaseInstallations.getInstance().getToken(forceRefresh)
 .addOnCompleteListener { task ->
 if (task.isSuccessful) {
 Log.d("Installations", "Installation auth token: " + task.result?.token)
 } else {
 Log.e("Installations", "Unable to get Installation auth token")
 }
 }

JavaScript

const installationToken = await firebase.installations()
 .getToken(/* forceRefresh */ true);
console.log(installationToken);

Dart

String token = await FirebaseInstallations.instance.getToken();

Monitor the Firebase installation ID lifecycle

During the normal operation of an app, Firebase installation IDs
(FIDs) don't require special monitoring.
However, apps that explicitly retrieve and use FIDs should
add logic to monitor the potential deletion or rotation of the
FID. Here are some cases where
FIDs could be deleted or rotated:

  • Uninstallation or reinstallation of the app, for instance when an end user

installs on a new device.

  • The end user clears the cache of the app or the device.
  • FID deletion is triggered in the backend due to app

inactivity (currently the threshold for this is 270 days of inactivity).

When apps experience FID rotation or deletion in these
kinds of cases, they are assigned a new FID. Also, the
installation auth token associated with a deleted FID is
deleted, regardless of its own maturity, and is replaced with a new
installation auth token.

Apps can monitor these changes and respond accordingly.

Swift

installationIDObserver = NotificationCenter.default.addObserver(
 forName: .InstallationIDDidChange,
 object: nil,
 queue: nil
) { (notification) in
 // Fetch new Installation ID
 Task {
 await self.fetchInstallationToken()
 }
}

Objective-C

__weak __auto_type weakSelf = self;
self.installationIDObserver = [[NSNotificationCenter defaultCenter]
 addObserverForName: FIRInstallationIDDidChangeNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull notification) {
 // Fetch new Installation ID
 [weakSelf fetchInstallationsID];
}];

An NSNotification named NSNotificationName.InstallationIDDidChange is
posted to the default NSNotificationCenter whenever a new
FID is assigned.

Android

Kotlin and Java clients should add retry logic to respond on failed calls
to retrieve the new FID.

JavaScript

Web apps can subscribe to the onIdChange hook.

Whenever a new FID is created, the subscribed callback is
triggered:

await firebase.installations().onIdChange((newId) => {
 console.log(newId);
 // TODO: Handle new installation ID.
});

Dart

FirebaseInstallations.instance.onIdChange.listen((token) {
 print('FID token: $token');
});

Migrate from Instance ID to Firebase installations

Prior to the introduction of Firebase installations, Firebase relied on the
Instance ID SDK for identifiers of app installs. Firebase installations
provides significant advantages over Instance ID in reliability, performance,
and security. Firebase apps that depend on the Instance ID SDK should migrate
to Firebase installations.

The migration process is different based on your app:

Apps that don't directly call Instance ID APIs can migrate by
updating their SDK versions.
Most Firebase apps fall into this category.

Apps that explicitly make API calls to Instance ID must update SDK versions
and make code changes to replace Instance ID
methods with their
Firebase installations or FCM equivalents. If your app uses
Instance ID to retrieve FCM registration tokens or explicitly uses
Instance ID to target app instances or for any other purpose, you'll need to
update your application code.

Currently, FIS
is backward-compatible with the legacy identifier Firebase Instance ID.
Deleting an IID
is an alternative method of requesting data deletion with
these Firebase SDKs:

  • Android SDKs earlier than February 27, 2020

This means that apps are not required to migrate to Firebase installations;
however, doing so is highly recommended.

Upgrading to minimum SDK versions for Firebase installations

To migrate from Instance ID to Firebase installations, make sure that your
applications use at least the listed minimum version numbers of the
following Firebase SDKs:

Firebase SDK

Minimum Android version

Minimum iOS version

Firebase Cloud Messaging

v20.3.0

v6.34.0

Remote Config

v19.2.0

v6.24.0

Google Analytics for Firebase \ (Measurement SDK)

v17.4.4

v6.18.0

In-App Messaging

v19.0.7

v6.24.0

Performance Monitoring

v19.0.8

v6.21.0

Crashlytics

v17.2.1

v6.23.0

ML Kit

v22.1.2

v6.28.0

Updating code that explicitly calls Instance ID APIs

If your Android or Apple app directly uses Instance ID SDK methods, you can
replace that usage with identical alternatives in the Firebase installations
SDK or the FCM SDK.

Retrieving an identifier

Methods to get Instance IDs are replaced with methods to get an installations
ID. For example:

Swift

Messaging.messaging().token { token, error in
 if let error = error {
 print("Error fetching remote FCM registration token: \(error)")
 } else if let token = token {
 print("Remote instance ID token: \(token)")
 }
}

Objective-C

[[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
 if (error != nil) {
 NSLog(@"Error fetching the remote FCM registration token: %@", error);
 } else {
 NSLog(@"Remote FCM registration token: %@", token);
 NSString* message =
 [NSString stringWithFormat:@"FCM registration token: %@", token];
 // display message
 NSLog(@"%@", message);
 }
}];

Java

FirebaseInstanceId.getInstance().getInstanceId()
 .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
 @Override
 public void onComplete(@NonNull Task<InstanceIdResult> task) {
 Log.d("IID_TOKEN", task.getResult().getToken());
 }
 });

Kotlin

FirebaseInstanceId.getInstance().instanceId
 .addOnSuccessListener { result ->
 Log.d("IID_TOKEN", result.token)
 }

Swift

do {
 let id = try await Installations.installations().installationID()
 print("Installation ID: \(id)")
} catch {
 print("Error fetching id: \(error)")
}

Objective-C

[[FIRInstallations installations] installationIDWithCompletion:^(NSString *identifier, NSError *error) {
 if (error != nil) {
 NSLog(@"Error fetching Installation ID %@", error);
 return;
 }
 NSLog(@"Installation ID: %@", identifier);
}];

Java

FirebaseInstallations.getInstance().getId()
 .addOnCompleteListener(new OnCompleteListener<String>() {
 @Override
 public void onComplete(@NonNull Task<String> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation ID: " + task.getResult());
 } else {
 Log.e("Installations", "Unable to get Installation ID");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().id.addOnCompleteListener { task ->
 if (task.isSuccessful) {
 Log.d("Installations", "Installation ID: " + task.result)
 } else {
 Log.e("Installations", "Unable to get Installation ID")
 }
}

Deleting an identifier

Methods to delete Instance IDs are replaced with methods to delete
Firebase installation IDs. For example:

Swift

InstanceID.instanceID().deleteID { error in
 if let error = error {
 print("Error deleting instance ID: \(error)")
 }
}

Objective-C

[FIRInstanceID instanceID] deleteIDWithHandler:^(NSError *error) {
 if error != nil {
 NSLog(@"Error deleting instance ID: %@", error);
 }
}];

Android

FirebaseInstanceId.deleteInstanceId();

Swift

func delete(completion: @escaping (Error?) -> Void)

Objective-C

- (void)deleteWithCompletion:(nonnull void (^)(NSError *_Nullable))completion;

Java

FirebaseInstallations.getInstance().delete()
 .addOnCompleteListener(new OnCompleteListener<Void>() {
 @Override
 public void onComplete(@NonNull Task<Void> task) {
 if (task.isSuccessful()) {
 Log.d("Installations", "Installation deleted");
 } else {
 Log.e("Installations", "Unable to delete Installation");
 }
 }
});

Kotlin

FirebaseInstallations.getInstance().delete().addOnCompleteListener { task ->
 if (task.isComplete) {
 Log.d("Installations", "Installation deleted")
 } else {
 Log.e("Installations", "Unable to delete Installation")
 }
}

Retrieving an FCM registration token

Prior to the introduction of Firebase Installations, FCM clients
retrieved registration tokens from Instance ID. Now, the FCM SDK
provides methods to retrieve the registration token.

Java

FirebaseInstanceId.getInstance().getInstanceId()
 .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
 @Override
 public void onComplete(@NonNull Task<InstanceIdResult> task) {
 if (!task.isSuccessful()) {
 Log.w(TAG, "getInstanceId failed", task.getException());
 return;
 }
 // Get new Instance ID token
 String token = task.getResult().getToken();
 // 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();
 }
 });

Kotlin

FirebaseInstanceId.getInstance().instanceId
 .addOnCompleteListener(OnCompleteListener { task ->
 if (!task.isSuccessful) {
 Log.w(TAG, "getInstanceId failed", task.exception)
 return@OnCompleteListener
 }
 // Get new Instance ID token
 val token = task.result?.token
 // Log and toast
 val msg = getString(R.string.msg_token_fmt, token)
 Log.d(TAG, msg)
 Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
 })

Swift

InstanceID.instanceID().instanceID { result, error in
 if let error = error {
 print("Error fetching instance ID: \(error)")
 } else if let result = result {
 print("Instance ID token: \(result.token)")
 }
}

Objective-C

[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
 NSError * _Nullable error) {
 if (error != nil) {
 NSLog(@"Error fetching instance ID: %@", error);
 } else {
 NSLog(@"Instance ID token: %@", result.token);
 }
}];

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();
 }
 });

Kotlin

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()
})

Swift

Messaging.messaging().token { token, error in
 if let error = error {
 print("Error fetching remote FCM registration token: \(error)")
 } else if let token = token {
 print("Remote instance ID token: \(token)")
 }
}

Objective-C

[[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
 if (error != nil) {
 NSLog(@"Error fetching the remote FCM registration token: %@", error);
 } else {
 NSLog(@"Remote FCM registration token: %@", token);
 NSString* message =
 [NSString stringWithFormat:@"FCM registration token: %@", token];
 // display message
 NSLog(@"%@", message);
 }
}];

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-10-07 UTC.

[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-10-07 UTC."],[],[]]

放大预览