如果您尚未將 Firebase 新增至 Android 專案,請先新增。
建立資料庫
在 Firebase 控制台中,依序前往「Databases & Storage」> 「即時資料庫」
按一下 [Create database] (建立資料庫)。
選取 Firebase Security Rules 的起始模式:
- 測試模式
適合用於開始使用行動和網頁用戶端程式庫,但允許任何人讀取及覆寫您的資料。測試完成後,請務必詳閱「瞭解 Firebase 即時資料庫規則」一節。
如要開始使用網頁、Apple 或 Android SDK,請選取測試模式。
- 鎖定模式
拒絕所有來自行動和網頁用戶端的讀寫要求。 通過驗證的應用程式伺服器仍可存取資料庫。
選擇資料庫的位置。
視資料庫的位置而定,新資料庫的網址會採用下列其中一種形式:
(適用於DATABASE_NAME.firebaseio.comus-central1中的資料庫) (適用於所有其他位置的資料庫)DATABASE_NAME.REGION.firebasedatabase.app
按一下「完成」。
啟用 Realtime Database 時,系統也會在 Cloud API Manager 中啟用 API。
在應用程式中加入 Realtime Database SDK
在模組 (應用程式層級) Gradle 檔案 (通常是<project>/<app-module>/build.gradle.kts 或 <project>/<app-module>/build.gradle) 中,新增 Android 專用 Realtime Database 程式庫的依附元件。建議使用 Firebase Android BoM 控制程式庫版本管理。
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:35.0.1")) // 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:23.0.0") }
設定「Realtime Database Security Rules」
Realtime Database提供宣告式規則語言,可讓您定義資料結構、索引方式,以及讀取和寫入資料的時機。
寫入資料庫
使用 getInstance() 擷取資料庫例項,並參照要寫入的位置。
Kotlin
// 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
// 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 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 this rule to fit the structure of your app.
-keepclassmembers class com.yourcompany.models.** {
*;
}
如需 ProGuard 相關問題或疑難排解的協助,請造訪 Guardsquare 社群論壇,向專家尋求協助。
準備發布
建議您在推出應用程式前,先瀏覽推出檢查清單,確保應用程式已準備就緒!
請務必啟用 App Check,確保只有您的應用程式可以存取資料庫。
後續步驟
- 瞭解如何為 Realtime Database 建立結構化資料
- 跨多個資料庫執行個體擴充資料。
- 讀取和寫入資料。
- 在 Firebase 控制台中查看資料庫。