將應用程式連結至 Firebase

如果您尚未將 Firebase 新增至 Android 專案,請先新增。

建立資料庫

  1. 前往 Firebase 控制台的「Realtime Database」部分。系統會提示您選取現有的 Firebase 專案。 按照資料庫建立工作流程操作。

  2. 選取 Firebase Security Rules 的起始模式:

    測試模式

    適合用來開始使用行動和網路用戶端程式庫,但允許任何人讀取及覆寫您的資料。測試完畢後,請務必查看「瞭解 Firebase 即時資料庫規則」一節。

    如要開始使用網頁、Apple 或 Android SDK,請選取 testmode。

    鎖定模式

    拒絕行動和網路用戶端的所有讀寫要求。 通過驗證的應用程式伺服器仍可存取資料庫。

  3. 選擇資料庫位置。

    資料庫位置而定,新資料庫的網址會採用下列其中一種形式:

    • DATABASE_NAME.firebaseio.com (適用於 us-central1 中的資料庫)

    • DATABASE_NAME.REGION.firebasedatabase.app (適用於所有其他位置的資料庫)

  4. 按一下「完成」

啟用 Realtime Database 時,系統也會在 Cloud API 管理工具中啟用 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:34.0.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:22.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,確保只有您的應用程式可以存取資料庫。

後續步驟