如果您尚未將 Firebase 新增至 Android 專案,請先完成這項作業。
建立資料庫
前往 Firebase 控制台的「Realtime Database」(即時資料庫) 部分。系統會提示您選取現有的 Firebase 專案。按照資料庫建立工作流程操作。
選取 Firebase 安全性規則的啟動模式:
- 測試模式
很適合開始使用行動和網路用戶端程式庫,但允許任何人讀取及覆寫您的資料。測試完成後,請務必查看「瞭解 Firebase 即時資料庫規則」一節。
如要開始使用網頁、Apple 或 Android SDK,請選取「testmode」。
- 鎖定模式
拒絕來自行動裝置和網路用戶端的所有讀寫作業。 但經驗證的應用程式伺服器仍然可以存取您的資料庫。
選擇資料庫的位置。
根據資料庫的位置,新資料庫的網址會採用下列其中一種格式:
(適用於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.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 程式庫版本。
(替代做法) 新增 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 控制台中查看資料庫。