将您的应用关联至 Firebase
将 Firebase 添加到您的 Android 项目(如果尚未添加)。
创建数据库
如果您还没有 Firebase 项目,请创建一个:在 Firebase 控制台中,点击添加项目,然后按照屏幕上的说明创建 Firebase 项目或将 Firebase 服务添加到现有 GCP 项目。
转到 Firebase 控制台的 Realtime Database 部分。 系统将会提示您选择现有 Firebase 项目。按照数据库创建工作流操作。
为您的 Firebase Security Rules 选择一个开始模式:
- 测试模式
此模式适合刚开始使用移动和 Web 客户端库的用户,但会允许任何人读取和覆盖您的数据。测试完成后,请务必查看了解 Firebase Realtime Database 规则部分。
如需开始使用 Web、iOS 或 Android SDK,请选择测试模式。
- 锁定模式
拒绝来自移动和 Web 客户端的所有读写操作。经过身份验证的应用服务器仍然可以访问您的数据库。
为数据库选择一个区域。根据您选择的区域,数据库命名空间的格式将是
<dbname>.firebaseio.com
或<dbname>.<regioncode>.firebasedatabase.app
。如需了解详情,请参阅为项目选择位置。点击完成。
如果启用 Realtime Database,也就在 Cloud API 管理器中启用了相应 API。
将 Realtime Database SDK 添加至您的应用
使用 Firebase Android BoM 在模块(应用级)Gradle 文件(通常为app/build.gradle
)中声明 Realtime Database Android 库的依赖项。
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.1.1') // Declare the dependency for the Realtime Database library // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-database' }
使用 Firebase Android BoM,可确保您的应用始终使用 Firebase Android 库的兼容版本。
(替代方法) 在不使用 BoM 的情况下声明 Firebase 库依赖项
如果您选择不使用 Firebase BoM,则必须在其依赖项行中指定每个 Firebase 库版本。
请注意,如果您在应用中使用多个 Firebase 库,我们强烈建议您使用 BoM 来管理库版本,从而确保所有版本都兼容。
dependencies { // Declare the dependency for the Realtime Database library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-database:19.5.1' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.1.1') // Declare the dependency for the Realtime Database library // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-database-ktx' }
使用 Firebase Android BoM,可确保您的应用始终使用 Firebase Android 库的兼容版本。
(替代方法) 在不使用 BoM 的情况下声明 Firebase 库依赖项
如果您选择不使用 Firebase BoM,则必须在其依赖项行中指定每个 Firebase 库版本。
请注意,如果您在应用中使用多个 Firebase 库,我们强烈建议您使用 BoM 来管理库版本,以确保所有版本都兼容。
dependencies { // Declare the dependency for the Realtime Database library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-database-ktx:19.5.1' }
配置 Realtime Database 规则
Realtime Database 提供了声明性规则语言,可用于定义数据的结构、将数据编入索引的方式,以及何时可以在其中读取和写入数据。
写入数据库
使用 getInstance()
检索数据库的实例并引用要向其中写入数据的位置。
Java
// Write a message to the database FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!");
Kotlin+KTX
// Write a message to the database val database = Firebase.database val myRef = database.getReference("message") myRef.setValue("Hello, World!")
您可以通过这种方式将一系列数据类型保存到数据库,包括 Java 对象。保存对象时,来自任何 getter 的响应将保存为此位置的子位置。
从数据库读取数据
如需实时更新应用数据,您应该将 ValueEventListener
添加到您刚创建的引用中。
此类中的 onDataChange()
方法在附加侦听器时触发一次,以后会在每次数据(包括子节点数据)发生更改时再次触发。
Java
// Read from the database myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. String value = dataSnapshot.getValue(String.class); Log.d(TAG, "Value is: " + value); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } });
Kotlin+KTX
// Read from the database myRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. val value = dataSnapshot.getValue<String>() Log.d(TAG, "Value is: $value") } override fun onCancelled(error: DatabaseError) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()) } })
可选:配置 ProGuard
在应用中结合使用 Firebase Realtime Database 与 ProGuard 时,您需要考虑将如何在模糊处理之后序列化和反序列化模型对象。如果您使用 DataSnapshot.getValue(Class)
或 DatabaseReference.setValue(Object)
读写数据,则需要向 proguard-rules.pro
文件添加规则:
# Add this global rule
-keepattributes Signature
# This rule will properly ProGuard all the model classes in
# the package com.yourcompany.models. Modify to fit the structure
# of your app.
-keepclassmembers class com.yourcompany.models.** {
*;
}
针对发布做好准备
发布应用之前,建议您浏览发布核对清单,确保您的应用已准备就绪!
后续步骤
- 了解如何为实时数据库设计数据结构
- 将数据扩展到多个数据库实例。
- 读取和写入数据。
- 在 Firebase 控制台中查看您的数据库。