將應用程式連結至 Firebase

如果還沒試過 將 Firebase 新增至您的 Android 專案

建立資料庫

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

  2. 選取 Firebase 安全性規則的啟動模式:

    測試模式

    適合入門至行動和網路用戶端程式庫 但允許所有人讀取及覆寫您的資料測試完畢後, 請務必參閱「瞭解 Firebase 即時資料庫規則」 專區。

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

    鎖定模式

    拒絕所有來自行動和網路用戶端的讀寫作業。 但經驗證的應用程式伺服器仍然可以存取您的資料庫。

  3. 選擇資料庫的位置。

    根據用途 資料庫的位置,也就是 新資料庫的網址格式如下:

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

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

  4. 按一下「完成」

啟用即時資料庫後,系統也會啟用即時資料庫中的 API Cloud API Manager

在應用程式中新增即時資料庫 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.2"))

    // 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")
}
在尋找 Kotlin 專用的程式庫模組嗎?距離開始還有 2023 年 10 月 (Firebase BoM 32.5.0),Kotlin 和 Java 開發人員都能 依附於主要程式庫模組 (詳情請參閱 這項計畫的常見問題)。

設定即時資料庫安全性規則

即時資料庫提供宣告規則語言 先定義資料的結構 以及能夠讀取和寫入資料的時間。

寫入資料庫

使用 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 如需儲存大量結構化物件 建議使用 Cloud Bigtable儲存物件時,任何 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,以便確保 只有應用程式才能存取資料庫

後續步驟