如果您还没有,请将 Firebase 添加到您的 Android 项目中。
创建数据库
导航到Firebase 控制台的实时数据库部分。系统会提示您选择一个现有的 Firebase 项目。遵循数据库创建工作流程。
为您的 Firebase 安全规则选择启动模式:
- 测试模式
适合开始使用移动和 Web 客户端库,但允许任何人读取和覆盖您的数据。测试后,请务必查看了解 Firebase 实时数据库规则部分。
要开始使用 Web、Apple 或 Android SDK,请选择测试模式。
- 锁定模式
拒绝来自移动和 Web 客户端的所有读取和写入。经过身份验证的应用程序服务器仍然可以访问您的数据库。
选择数据库的位置。
根据数据库的位置,新数据库的 URL 将采用以下形式之一:
DATABASE_NAME .firebaseio.com
(对于us-central1
中的数据库)DATABASE_NAME . REGION .firebasedatabase.app
(对于所有其他位置的数据库)
单击完成。
当您启用实时数据库时,它还会启用Cloud API Manager中的 API。
将实时数据库 SDK 添加到您的应用
在您的模块(应用程序级)Gradle 文件(通常为<project>/<app-module>/build.gradle
)中,添加实时数据库 Android 库的依赖项。我们建议使用Firebase Android BoM来控制库版本。 Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.0') // Add 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 { // Add 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:20.1.0' }
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.0') // Add 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 { // Add 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:20.1.0' }
配置实时数据库规则
实时数据库提供了一种声明性规则语言,允许您定义数据的结构、索引方式以及何时可以读取和写入数据。
写入你的数据库
使用getInstance()
检索数据库实例并引用要写入的位置。
Kotlin+KTX
// Write a message to the database val database = Firebase.database val myRef = database.getReference("message") myRef.setValue("Hello, World!")
Java
// Write a message to the database FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("message"); myRef.setValue("Hello, World!");
您可以通过这种方式将一系列数据类型保存到数据库中,包括 Java 对象。当您保存一个对象时,来自任何 getter 的响应将被保存为该位置的子对象。
从你的数据库中读取
要使您的应用程序数据实时更新,您应该向刚刚创建的引用添加一个ValueEventListener
。
此类中的onDataChange()
方法在附加侦听器时触发一次,并在每次数据更改时再次触发,包括子项。
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()) } })
Java
// Read from the database myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull 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(@NonNull DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } });
可选:配置 ProGuard
在您的应用中将 Firebase 实时数据库与 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 this rule to fit the structure of your app.
-keepclassmembers class com.yourcompany.models.** {
*;
}
要获得与 ProGuard 相关的问题或问题的帮助,请访问Guardsquare 社区论坛以获得专家的帮助。
准备发布
在启动您的应用程序之前,我们建议您仔细检查我们的启动清单以确保您的应用程序已准备就绪!
请务必启用App Check以帮助确保只有您的应用程序可以访问您的数据库。
下一步
- 了解如何为实时数据库构建数据结构
- 跨多个数据库实例扩展您的数据。
- 读写数据。
- 在 Firebase 控制台中查看您的数据库。