如果您尚未將 Firebase 新增至 Android 專案,請先完成這項作業。
建立資料庫
前往 Firebase 控制台的「Realtime Database」(即時資料庫) 部分。系統會提示您選取現有的 Firebase 專案。按照資料庫建立工作流程操作。
選取 Firebase 安全性規則的啟動模式:
- 測試模式
適合開始使用行動和網路用戶端程式庫,但允許所有人讀取及覆寫您的資料。測試後,請務必詳閱「瞭解 Firebase 即時資料庫規則」一節。
如要開始使用網頁版、Apple 或 Android SDK,請選取「測試模式」。
- 鎖定模式
拒絕來自行動及網路用戶端的所有讀取和寫入作業。 通過驗證的應用程式伺服器仍可存取資料庫。
選擇資料庫位置。
新資料庫的網址會是下列其中一種格式,視資料庫位置而定:
(適用於DATABASE_NAME.firebaseio.com
us-central1
中的資料庫) (用於所有其他位置的資料庫)DATABASE_NAME.REGION.firebasedatabase.app
點選「完成」。
啟用即時資料庫時,也會在 Cloud API Manager 中啟用 API。
將即時資料庫 SDK 新增至應用程式
在模組 (應用程式層級) Gradle 檔案 (通常是<project>/<app-module>/build.gradle.kts
或 <project>/<app-module>/build.gradle
) 中,新增 Android 即時資料庫程式庫的依附元件。建議您使用 Firebase Android BoM 來控管程式庫版本管理。
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.1.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 程式庫版本。
(替代方法) 新增 Firebase 程式庫依附元件,「不必」使用 BoM
如果選擇不使用 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:21.0.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 控制台中查看資料庫。