1. 概述
圖片:工作友好的聊天應用程序。
歡迎來到友好聊天代碼實驗室。在此 Codelab 中,您將學習如何使用 Firebase 平台在 Android 上創建聊天應用。
你將學到什麼
- 如何使用 Firebase 身份驗證允許用戶登錄。
- 如何使用 Firebase 實時數據庫同步數據。
- 如何在 Cloud Storage for Firebase 中存儲二進製文件。
- 如何使用 Firebase 本地模擬器套件通過 Firebase 開發 Android 應用。
你需要什麼
- 最新的Android Studio版本。
- 帶有 Android 5.0+ 的Android 模擬器。
- Node.js 版本 10 或更高版本(以使用模擬器套件)。
- Java 8 或更高版本。要安裝 Java,請使用這些說明;要檢查您的版本,請運行
java -version
。 - 熟悉 Kotlin 編程語言。
2. 獲取示例代碼
克隆存儲庫
從命令行克隆 GitHub 存儲庫:
$ git clone https://github.com/firebase/codelab-friendlychat-android
導入Android Studio
在 Android Studio 中,選擇File > Open ,然後選擇build-android-start
目錄 ( )從您下載示例代碼的目錄中。
您現在應該在 Android Studio 中打開build-android-start
項目。如果您看到有關google-services.json
文件丟失的警告,請不要擔心。它將在稍後的步驟中添加。
檢查依賴關係
在此 Codelab 中,您需要的所有依賴項均已添加,但了解如何將 Firebase SDK 添加到您的應用中非常重要:
構建.gradle.kts
plugins {
id("com.android.application") version "8.0.0" apply false
id("com.android.library") version "8.0.0" apply false
id("org.jetbrains.kotlin.android") version "1.8.20" apply false
// The google-services plugin is required to parse the google-services.json file
id("com.google.gms.google-services") version "4.3.15" apply false
}
應用程序/build.gradle.kts
plugins {
id("com.android.application")
id("kotlin-android")
id("com.google.gms.google-services")
}
android {
// ...
}
dependencies {
// ...
// Google Sign In SDK
implementation("com.google.android.gms:play-services-auth:20.5.0")
// Firebase SDK
implementation(platform("com.google.firebase:firebase-bom:32.0.0"))
implementation("com.google.firebase:firebase-database-ktx")
implementation("com.google.firebase:firebase-storage-ktx")
implementation("com.google.firebase:firebase-auth-ktx")
// Firebase UI Library
implementation("com.firebaseui:firebase-ui-auth:8.0.2")
implementation("com.firebaseui:firebase-ui-database:8.0.2")
}
3. 安裝 Firebase CLI
在此 Codelab 中,您將使用Firebase Emulator Suite在本地模擬 Firebase Auth、實時數據庫和雲存儲。這提供了一個安全、快速且免費的本地開發環境來構建您的應用程序。
安裝 Firebase CLI
首先,您需要安裝Firebase CLI 。如果您使用的是 macOS 或 Linux,則可以運行以下 cURL 命令:
curl -sL https://firebase.tools | bash
如果您使用的是 Windows,請閱讀安裝說明以獲取獨立的二進製文件或通過npm
安裝。
安裝 CLI 後,運行firebase --version
應報告9.0.0
或更高版本:
$ firebase --version 9.0.0
登錄
運行firebase login
將 CLI 連接到您的 Google 帳戶。這將打開一個新的瀏覽器窗口以完成登錄過程。確保選擇您之前創建 Firebase 項目時使用的相同帳戶。
4. 連接到 Firebase 模擬器套件
啟動模擬器
在終端中,從本地codelab-friendlychat-android
目錄的根目錄運行以下命令:
firebase emulators:start --project=demo-friendlychat-android
您應該會看到一些像這樣的日誌。端口值在firebase.json
文件中定義,該文件包含在克隆的示例代碼中。
$ firebase emulators:start --project=demo-friendlychat-android
i emulators: Starting emulators: auth, database, storage
i emulators: Detected demo project ID "demo-friendlychat-android", emulated services will use a demo configuration and attempts to access non-emulated services for this project will fail.
i database: Database Emulator logging to database-debug.log
i ui: Emulator UI logging to ui-debug.log
┌─────────────────────────────────────────────────────────────┐
│ ✔ All emulators ready! It is now safe to connect your app. │
│ i View Emulator UI at http://localhost:4000 │
└─────────────────────────────────────────────────────────────┘
┌────────────────┬────────────────┬────────────────────────────────┐
│ Emulator │ Host:Port │ View in Emulator UI │
├────────────────┼────────────────┼────────────────────────────────┤
│ Authentication │ localhost:9099 │ http://localhost:4000/auth │
├────────────────┼────────────────┼────────────────────────────────┤
│ Database │ localhost:9000 │ http://localhost:4000/database │
├────────────────┼────────────────┼────────────────────────────────┤
│ Storage │ localhost:9199 │ http://localhost:4000/storage │
└────────────────┴────────────────┴────────────────────────────────┘
Emulator Hub running at localhost:4400
Other reserved ports: 4500
Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.
在 Web 瀏覽器中導航到http://localhost:4000以查看 Firebase Emulator Suite UI:
讓emulators:start
命令在 Codelab 的其餘部分運行。
連接您的應用程序
在 Android Studio 中,打開MainActivity.kt
,然後在onCreate
方法中添加以下代碼:
// When running in debug mode, connect to the Firebase Emulator Suite.
// "10.0.2.2" is a special IP address which allows the Android Emulator
// to connect to "localhost" on the host computer. The port values (9xxx)
// must match the values defined in the firebase.json file.
if (BuildConfig.DEBUG) {
Firebase.database.useEmulator("10.0.2.2", 9000)
Firebase.auth.useEmulator("10.0.2.2", 9099)
Firebase.storage.useEmulator("10.0.2.2", 9199)
}
5. 運行啟動應用程序
添加 google-services.json
為了讓您的 Android 應用連接到 Firebase,您必須在 Android 項目的app
文件夾中添加google-services.json
文件。出於本 Codelab 的目的,我們提供了一個模擬 JSON 文件,該文件將允許您連接到 Firebase 模擬器套件。
將mock-google-services.json
文件複製到build-android-start/app
文件夾中作為google-services.json
:
cp mock-google-services.json build-android-start/app/google-services.json
在此 Codelab 的最後一步中,您將學習如何創建真正的 Firebase 項目和 Firebase Android 應用,以便您可以使用自己的配置替換此模擬 JSON 文件。
運行應用程序
現在您已將項目導入 Android Studio 並添加了 Firebase 配置 JSON 文件,您已準備好首次運行該應用。
- 啟動您的 Android 模擬器。
- 在 Android Studio 中,單擊運行(
)在工具欄中。
該應用程序應該在您的 Android 模擬器上啟動。此時,您應該看到一個空的消息列表,並且發送和接收消息將不起作用。在此 Codelab 的下一步中,您將對用戶進行身份驗證,以便他們可以使用友好聊天。
6. 啟用身份驗證
此應用程序將使用 Firebase 實時數據庫來存儲所有聊天消息。不過,在添加數據之前,我們應該確保應用程序是安全的,並且只有經過身份驗證的用戶才能發布消息。在此步驟中,我們將啟用 Firebase 身份驗證並配置實時數據庫安全規則。
添加基本登錄功能
接下來,我們將向應用程序添加一些基本的 Firebase 身份驗證代碼,以檢測用戶並實現登錄屏幕。
檢查當前用戶
首先將以下實例變量添加到MainActivity.kt
類中:
MainActivity.kt
// Firebase instance variables
private lateinit var auth: FirebaseAuth
現在,讓我們修改MainActivity
,以便在用戶打開應用程序且未經身份驗證時將其發送到登錄屏幕。將binding
附加到視圖後,將以下內容添加到onCreate()
方法中:
MainActivity.kt
// Initialize Firebase Auth and check if the user is signed in
auth = Firebase.auth
if (auth.currentUser == null) {
// Not signed in, launch the Sign In activity
startActivity(Intent(this, SignInActivity::class.java))
finish()
return
}
我們還想檢查用戶是否在onStart()
期間登錄:
MainActivity.kt
public override fun onStart() {
super.onStart()
// Check if user is signed in.
if (auth.currentUser == null) {
// Not signed in, launch the Sign In activity
startActivity(Intent(this, SignInActivity::class.java))
finish()
return
}
}
然後實現getUserPhotoUrl()
和getUserName()
方法以返回有關當前經過身份驗證的 Firebase 用戶的相應信息:
MainActivity.kt
private fun getPhotoUrl(): String? {
val user = auth.currentUser
return user?.photoUrl?.toString()
}
private fun getUserName(): String? {
val user = auth.currentUser
return if (user != null) {
user.displayName
} else ANONYMOUS
}
然後實現signOut()
方法來處理註銷按鈕:
MainActivity.kt
private fun signOut() {
AuthUI.getInstance().signOut()
startActivity(Intent(this, SignInActivity::class.java))
finish()
}
現在,我們已準備好所有邏輯,以便在必要時將用戶發送到登錄屏幕。接下來我們需要實現登錄屏幕以正確驗證用戶身份。
實施登錄屏幕
打開文件SignInActivity.kt
。這裡使用一個簡單的登錄按鈕來啟動身份驗證。在本部分中,您將使用 FirebaseUI 實現登錄邏輯。
在// Firebase instance variables
註釋下的SignInActivity
類中添加 Auth 實例變量:
登錄活動.kt
// Firebase instance variables
private lateinit var auth: FirebaseAuth
然後,編輯onCreate()
方法以按照與MainActivity
中相同的方式初始化 Firebase:
登錄活動.kt
// Initialize FirebaseAuth
auth = Firebase.auth
將ActivityResultLauncher
字段添加到SignInActivity
:
登錄活動.kt
// ADD THIS
private val signIn: ActivityResultLauncher<Intent> =
registerForActivityResult(FirebaseAuthUIActivityResultContract(), this::onSignInResult)
override fun onCreate(savedInstanceState: Bundle?) {
// ...
}
接下來,編輯onStart()
方法以啟動 FirebaseUI 登錄流程:
登錄活動.kt
public override fun onStart() {
super.onStart()
// If there is no signed in user, launch FirebaseUI
// Otherwise head to MainActivity
if (Firebase.auth.currentUser == null) {
// Sign in with FirebaseUI, see docs for more details:
// https://firebase.google.com/docs/auth/android/firebaseui
val signInIntent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setLogo(R.mipmap.ic_launcher)
.setAvailableProviders(listOf(
AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build(),
))
.build()
signIn.launch(signInIntent)
} else {
goToMainActivity()
}
}
接下來,實現onSignInResult
方法來處理登錄結果。如果登錄結果成功,則繼續進入MainActivity
:
登錄活動.kt
private fun onSignInResult(result: FirebaseAuthUIAuthenticationResult) {
if (result.resultCode == RESULT_OK) {
Log.d(TAG, "Sign in successful!")
goToMainActivity()
} else {
Toast.makeText(
this,
"There was an error signing in",
Toast.LENGTH_LONG).show()
val response = result.idpResponse
if (response == null) {
Log.w(TAG, "Sign in canceled")
} else {
Log.w(TAG, "Sign in error", response.error)
}
}
}
就是這樣!您只需幾次方法調用即可使用 FirebaseUI 實現身份驗證,而無需管理任何服務器端配置。
測試你的工作
在 Android 模擬器上運行該應用程序。您應該立即轉到登錄屏幕。點擊使用電子郵件登錄按鈕,然後創建一個帳戶。如果一切都正確實施,您應該會被發送到消息屏幕。
登錄後,在瀏覽器中打開 Firebase Emulator Suite UI,然後單擊“身份驗證”選項卡以查看第一個登錄的用戶帳戶。
7. 閱讀消息
在此步驟中,我們將添加讀取和顯示實時數據庫中存儲的消息的功能。
導入示例消息
- 在 Firebase Emulator Suite UI 中,選擇“實時數據庫”選項卡。
- 將
initial_messages.json
文件從 Codelab 存儲庫的本地副本拖放到數據查看器中。
現在,數據庫的messages
節點下應該有一些消息。
讀取數據
同步消息
在本節中,我們添加代碼,通過以下方式將新添加的消息同步到應用程序 UI:
- 初始化 Firebase 實時數據庫並添加偵聽器來處理對數據所做的更改。
- 更新
RecyclerView
適配器以便顯示新消息。 - 將數據庫實例變量與
MainActivity
類中的其他 Firebase 實例變量一起添加:
MainActivity.kt
// Firebase instance variables
// ...
private lateinit var db: FirebaseDatabase
private lateinit var adapter: FriendlyMessageAdapter
使用下面定義的代碼修改註釋// Initialize Realtime Database and FirebaseRecyclerAdapter
下 MainActivity 的onCreate()
方法。此代碼添加實時數據庫中的所有現有消息,然後偵聽 Firebase 實時數據庫中messages
路徑下的新子條目。它為每條消息添加一個新元素到 UI:
MainActivity.kt
// Initialize Realtime Database
db = Firebase.database
val messagesRef = db.reference.child(MESSAGES_CHILD)
// The FirebaseRecyclerAdapter class and options come from the FirebaseUI library
// See: https://github.com/firebase/FirebaseUI-Android
val options = FirebaseRecyclerOptions.Builder<FriendlyMessage>()
.setQuery(messagesRef, FriendlyMessage::class.java)
.build()
adapter = FriendlyMessageAdapter(options, getUserName())
binding.progressBar.visibility = ProgressBar.INVISIBLE
manager = LinearLayoutManager(this)
manager.stackFromEnd = true
binding.messageRecyclerView.layoutManager = manager
binding.messageRecyclerView.adapter = adapter
// Scroll down when a new message arrives
// See MyScrollToBottomObserver for details
adapter.registerAdapterDataObserver(
MyScrollToBottomObserver(binding.messageRecyclerView, adapter, manager)
)
接下來在FriendlyMessageAdapter.kt
類中實現內部類MessageViewHolder()
中的bind()
方法:
友好消息適配器.kt
inner class MessageViewHolder(private val binding: MessageBinding) : ViewHolder(binding.root) {
fun bind(item: FriendlyMessage) {
binding.messageTextView.text = item.text
setTextColor(item.name, binding.messageTextView)
binding.messengerTextView.text = if (item.name == null) ANONYMOUS else item.name
if (item.photoUrl != null) {
loadImageIntoView(binding.messengerImageView, item.photoUrl!!)
} else {
binding.messengerImageView.setImageResource(R.drawable.ic_account_circle_black_36dp)
}
}
...
}
我們還需要顯示圖像消息,因此還要在內部類ImageMessageViewHolder()
中實現bind()
方法:
友好消息適配器.kt
inner class ImageMessageViewHolder(private val binding: ImageMessageBinding) :
ViewHolder(binding.root) {
fun bind(item: FriendlyMessage) {
loadImageIntoView(binding.messageImageView, item.imageUrl!!)
binding.messengerTextView.text = if (item.name == null) ANONYMOUS else item.name
if (item.photoUrl != null) {
loadImageIntoView(binding.messengerImageView, item.photoUrl!!)
} else {
binding.messengerImageView.setImageResource(R.drawable.ic_account_circle_black_36dp)
}
}
}
最後,返回MainActivity
,開始和停止偵聽來自 Firebase 實時數據庫的更新。更新MainActivity
中的onPause()
和onResume()
方法,如下所示:
MainActivity.kt
public override fun onPause() {
adapter.stopListening()
super.onPause()
}
public override fun onResume() {
super.onResume()
adapter.startListening()
}
測試同步消息
- 單擊運行(
)。
- 在模擬器套件 UI 中,返回“實時數據庫”選項卡,然後手動添加新消息。確認該消息顯示在您的 Android 應用程序中:
恭喜,您剛剛將實時數據庫添加到您的應用程序中!
8. 發送消息
實現短信發送
在本部分中,您將為應用程序用戶添加發送短信的功能。下面的代碼片段偵聽發送按鈕上的單擊事件,使用消息字段的內容創建一個新的FriendlyMessage
對象,並將消息推送到數據庫。 push()
方法將自動生成的 ID 添加到推送對象的路徑中。這些 ID 是連續的,確保新消息將添加到列表的末尾。
在MainActivity
類的onCreate()
方法中更新發送按鈕的點擊監聽器。此代碼已位於onCreate()
方法的底部。更新onClick()
主體以匹配以下代碼:
MainActivity.kt
// Disable the send button when there's no text in the input field
// See MyButtonObserver for details
binding.messageEditText.addTextChangedListener(MyButtonObserver(binding.sendButton))
// When the send button is clicked, send a text message
binding.sendButton.setOnClickListener {
val friendlyMessage = FriendlyMessage(
binding.messageEditText.text.toString(),
getUserName(),
getPhotoUrl(),
null /* no image */
)
db.reference.child(MESSAGES_CHILD).push().setValue(friendlyMessage)
binding.messageEditText.setText("")
}
實現圖片消息發送
在本部分中,您將為應用程序用戶添加發送圖像消息的功能。創建圖像消息通過以下步驟完成:
- 選擇圖片
- 處理圖像選擇
- 將臨時圖像消息寫入實時數據庫
- 開始上傳選定的圖像
- 上傳完成後,將圖像消息 URL 更新為上傳圖像的 URL
選擇圖像
為了添加圖像,此 Codelab 使用 Cloud Storage for Firebase。雲存儲是存儲應用程序二進制數據的好地方。
處理圖像選擇並寫入臨時消息
一旦用戶選擇了圖像,就會啟動圖像選擇Intent
。這已經在onCreate()
方法末尾的代碼中實現了。完成後,它會調用MainActivity
的onImageSelected()
方法。使用下面的代碼片段,您將向數據庫寫入一條帶有臨時圖像 URL 的消息,指示圖像正在上傳。
MainActivity.kt
private fun onImageSelected(uri: Uri) {
Log.d(TAG, "Uri: $uri")
val user = auth.currentUser
val tempMessage = FriendlyMessage(null, getUserName(), getPhotoUrl(), LOADING_IMAGE_URL)
db.reference
.child(MESSAGES_CHILD)
.push()
.setValue(
tempMessage,
DatabaseReference.CompletionListener { databaseError, databaseReference ->
if (databaseError != null) {
Log.w(
TAG, "Unable to write message to database.",
databaseError.toException()
)
return@CompletionListener
}
// Build a StorageReference and then upload the file
val key = databaseReference.key
val storageReference = Firebase.storage
.getReference(user!!.uid)
.child(key!!)
.child(uri.lastPathSegment!!)
putImageInStorage(storageReference, uri, key)
})
}
上傳圖片並更新消息
將方法putImageInStorage()
添加到MainActivity
。在onImageSelected()
中調用它來啟動所選圖像的上傳。上傳完成後,您將更新消息以使用適當的圖像。
MainActivity.kt
private fun putImageInStorage(storageReference: StorageReference, uri: Uri, key: String?) {
// First upload the image to Cloud Storage
storageReference.putFile(uri)
.addOnSuccessListener(
this
) { taskSnapshot -> // After the image loads, get a public downloadUrl for the image
// and add it to the message.
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { uri ->
val friendlyMessage =
FriendlyMessage(null, getUserName(), getPhotoUrl(), uri.toString())
db.reference
.child(MESSAGES_CHILD)
.child(key!!)
.setValue(friendlyMessage)
}
}
.addOnFailureListener(this) { e ->
Log.w(
TAG,
"Image upload task was unsuccessful.",
e
)
}
}
測試發送消息
- 在 Android Studio 中,單擊
運行按鈕。
- 在 Android 模擬器中,輸入消息,然後點擊發送按鈕。新消息應該在應用程序 UI 和 Firebase 模擬器套件 UI 中可見。
- 在 Android 模擬器中,點擊“+”圖像以從您的設備中選擇圖像。新消息應首先顯示佔位符圖像,然後在圖像上傳完成後顯示所選圖像。新消息還應該在模擬器套件 UI 中可見,特別是作為“實時數據庫”選項卡中的對象和“存儲”選項卡中的 blob。
9. 恭喜!
您剛剛使用 Firebase 構建了一個實時聊天應用程序!
你學到了什麼
- Firebase 身份驗證
- Firebase 實時數據庫
- Firebase 雲存儲
接下來,嘗試使用您在此 Codelab 中學到的知識將 Firebase 添加到您自己的 Android 應用中!要了解有關 Firebase 的更多信息,請訪問firebase.google.com 。
如果您想了解如何設置真實的Firebase 項目並使用真實的Firebase 資源(而不是演示項目和僅模擬資源),請繼續執行下一步。
注意:即使您設置了真正的 Firebase 項目,特別是當您開始構建真正的應用程序時,我們也建議您使用 Firebase 本地模擬器套件進行開發和測試。
10. 可選:創建並設置 Firebase 項目
在此步驟中,您將創建一個真正的 Firebase 項目和一個用於此 Codelab 的 Firebase Android 應用。您還需要將應用特定的 Firebase 配置添加到您的應用中。最後,您將設置真正的 Firebase 資源以與您的應用一起使用。
創建 Firebase 項目
- 在瀏覽器中,轉到Firebase 控制台。
- 選擇添加項目。
- 選擇或輸入項目名稱。您可以使用任何您想要的名稱。
- 此 Codelab 不需要 Google Analytics,因此您可以跳過為您的項目啟用它。
- 單擊“創建項目” 。當您的項目準備就緒時,單擊“繼續” 。
將 Firebase 添加到您的 Android 項目
在開始此步驟之前,請獲取應用程序的 SHA1 哈希值。從本地build-android-start
目錄運行以下命令來確定調試密鑰的 SHA1:
./gradlew signingReport Store: /Users/<username>/.android/debug.keystore Alias: AndroidDebugKey MD5: A5:88:41:04:8F:06:59:6A:AE:33:76:87:AA:AD:19:23 SHA1: A7:89:F5:06:A8:07:A1:22:EC:90:6A:A6:EA:C3:D4:8B:3A:30:AB:18 SHA-256: 05:A2:2A:35:EE:F2:51:23:72:4D:72:67:A5:6A:8A:58:22:2C:00:A6:AB:F6:45:D5:A1:82:D8:90:A4:69:C8:FE Valid until: Wednesday, August 10, 2044
您應該看到類似上面的一些輸出。重要的一行是SHA1
哈希值。如果您無法找到 SHA1 哈希值,請參閱此頁面了解更多信息。
返回 Firebase 控制台,然後按照以下步驟將您的 Android 項目註冊到 Firebase 項目:
- 在新項目的概述屏幕中,單擊 Android 圖標以啟動設置工作流程:
- 在下一個屏幕上,輸入
com.google.firebase.codelab.friendlychat
作為應用程序的包名稱。 - 單擊Register App ,然後單擊Download google-services.json以下載您的 Firebase 配置文件。
- 將
google-services.json
文件複製到 Android 項目的app
目錄中。 - 跳過控制台設置工作流程中顯示的後續步驟(這些步驟已在
build-android-start
項目中為您完成)。 - 通過將項目與 Gradle 文件同步,確保所有依賴項均可用於您的應用程序。從 Android Studio 工具欄中,選擇File > Sync Project with Gradle Files 。您可能還需要運行構建/清理項目和構建/重建項目才能進行配置更改。
配置 Firebase 身份驗證
在您的應用可以代表用戶訪問 Firebase 身份驗證 API 之前,您需要啟用 Firebase 身份驗證以及要在應用中使用的登錄提供商。
- 在Firebase 控制台中,從左側導航面板中選擇身份驗證。
- 選擇登錄方法選項卡。
- 單擊電子郵件/密碼,然後將開關切換為啟用(藍色)。
- 單擊Google ,然後將開關切換為啟用(藍色)並設置項目支持電子郵件。
如果您稍後在此 Codelab 中遇到錯誤並顯示消息“CONFIGURATION_NOT_FOUND”,請返回此步驟並仔細檢查您的工作。
配置實時數據庫
此 Codelab 中的應用將聊天消息存儲在 Firebase 實時數據庫中。在本部分中,我們將創建一個數據庫並通過稱為 Firebase 安全規則的 JSON 配置語言配置其安全性。
- 在Firebase 控制台中,從左側導航面板中選擇實時數據庫。
- 單擊創建數據庫以創建新的實時數據庫實例。出現提示時,選擇
us-central1
區域,然後單擊Next 。 - 當提示有關安全規則時,選擇鎖定模式,然後單擊啟用。
- 創建數據庫實例後,選擇“規則”選項卡,然後使用以下內容更新規則配置:
{ "rules": { "messages": { ".read": "auth.uid != null", ".write": "auth.uid != null" } } }
有關安全規則如何工作的更多信息(包括有關“auth”變量的文檔),請參閱實時數據庫安全文檔。
為 Firebase 配置雲存儲
- 在Firebase 控制台中,從左側導航面板中選擇存儲。
- 單擊開始為您的項目啟用雲存儲。
- 按照對話框中的步驟使用建議的默認值設置您的存儲桶。
連接到 Firebase 資源
在此 Codelab 的前面步驟中,您將以下內容添加到MainActivity.kt
中。此條件塊將您的 Android 項目連接到 Firebase Emulator Suite。
// REMOVE OR DISABLE THIS
if (BuildConfig.DEBUG) {
Firebase.database.useEmulator("10.0.2.2", 9000)
Firebase.auth.useEmulator("10.0.2.2", 9099)
Firebase.storage.useEmulator("10.0.2.2", 9199)
}
如果您想將您的應用連接到新的真實Firebase 項目及其真實Firebase 資源,您可以刪除此塊或在發布模式下運行您的應用,以便BuildConfig.DEBUG
為false
。