將您的應用連接到 Firebase

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

建立資料庫

  1. 導覽至Firebase 控制台「即時資料庫」部分。系統會提示您選擇現有的 Firebase 專案。遵循資料庫建立工作流程。

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

    測試模式

    適合開始使用行動和 Web 用戶端庫,但允許任何人讀取和覆蓋您的資料。測試後,請務必查看了解 Firebase 即時資料庫規則部分。

    若要開始使用 Web、Apple 或 Android SDK,請選擇測試模式。

    鎖定模式

    拒絕來自行動和 Web 用戶端的所有讀取和寫入。經過身份驗證的應用程式伺服器仍然可以存取您的資料庫。

  3. 選擇資料庫的位置。

    根據資料庫的位置,新資料庫的 URL 將採用以下形式之一:

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

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

  4. 按一下“完成”

啟用即時資料庫時,也會啟用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:32.7.4"))

    // 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:20.3.1")
}
正在尋找 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 物件。當您儲存物件時,任何 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 社群論壇以獲得專家的協助。

準備發射

在啟動您的應用程式之前,我們建議您仔細閱讀我們的啟動清單,以確保您的應用程式已準備就緒!

請務必啟用應用程式檢查,以協助確保只有您的應用程式可以存取您的資料庫。

下一步