將您的應用連接到 Firebase,將您的應用連接到 Firebase

如果您還沒有,請將 Firebase 添加到您的 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 )中,添加實時數據庫 Android 庫的依賴項。我們建議使用Firebase Android BoM來控制庫版本。

Kotlin+KTX

dependencies {
    // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:32.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-ktx'
}

通過使用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-ktx:20.2.2'
}

Java

dependencies {
    // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:32.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 庫。

(備選)在不使用 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.2.2'
}

配置實時數據庫安全規則

實時數據庫提供了一種聲明性規則語言,允許您定義數據的結構、索引方式以及何時可以讀取和寫入數據。

寫入你的數據庫

使用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以幫助確保只有您的應用程序可以訪問您的數據庫。

下一步