一、概述
圖片:Working Friendly Chat 應用程序。
歡迎來到 Friendly Chat 代碼實驗室。在此 Codelab 中,您將學習如何使用 Firebase 平台在 Android 上創建聊天應用。
你會學到什麼
- 如何使用 Firebase 身份驗證允許用戶登錄。
- 如何使用 Firebase 實時數據庫同步數據。
- 如何在 Cloud Storage for Firebase 中存儲二進製文件。
- 如何使用 Firebase Local Emulator Suite 通過 Firebase 開發 Android 應用程序。
你需要什麼
- Android Studio版本 4.2+。
- Android 模擬器Android 5.0+。
- 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
文件的警告,請不要擔心。它將在稍後的步驟中添加。
檢查依賴關係
在此代碼實驗室中,您需要的所有依賴項都已為您添加,但了解如何將 Firebase SDK 添加到您的應用很重要:
構建.gradle
buildscript {
// ...
dependencies {
classpath 'com.android.tools.build:gradle:7.2.2'
// The google-services plugin is required to parse the google-services.json file
classpath 'com.google.gms:google-services:4.3.13'
}
}
應用程序/build.gradle
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.2.0'
// Firebase SDK
implementation platform('com.google.firebase:firebase-bom:30.3.2')
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.1'
implementation 'com.firebaseui:firebase-ui-database:8.0.1'
}
3. 安裝 Firebase CLI
在此 Codelab 中,您將使用Firebase 模擬器套件在本地模擬 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 Emulator Suite。
將mock-google-services.json
文件作為google-services.json
複製到build-android-start/app
文件夾中:
cp mock-google-services.json build-android-start/app/google-services.json
在此 Codelab 的最後一步,您將學習如何創建一個真正的 Firebase 項目和 Firebase Android 應用程序,以便您可以用您自己的配置替換這個模擬 JSON 文件。
運行應用
既然您已將項目導入 Android Studio 並添加了 Firebase 配置 JSON 文件,您就可以首次運行該應用程序了。
- 啟動你的安卓模擬器。
- 在 Android Studio 中,點擊運行(
) 在工具欄中。
該應用程序應在您的 Android 模擬器上啟動。此時,您應該看到一個空的消息列表,發送和接收消息將不起作用。在此 Codelab 的下一步中,您將對用戶進行身份驗證,以便他們可以使用 Friendly Chat。
6.啟用身份驗證
此應用程序將使用 Firebase 實時數據庫來存儲所有聊天消息。不過,在我們添加數據之前,我們應該確保該應用程序是安全的,並且只有經過身份驗證的用戶才能發布消息。在此步驟中,我們將啟用 Firebase 身份驗證並配置實時數據庫安全規則。
添加基本登錄功能
接下來,我們將向應用程序添加一些基本的 Firebase 身份驗證代碼,以檢測用戶並實現登錄屏幕。
檢查當前用戶
首先在MainActivity.kt
類中添加如下實例變量:
主活動.kt
// Firebase instance variables
private lateinit var auth: FirebaseAuth
現在讓我們修改MainActivity
以便在用戶打開應用程序且未通過身份驗證時將用戶發送到登錄屏幕。將binding
附加到視圖後,將以下內容添加到onCreate()
方法:
主活動.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()
期間登錄:
主活動.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 用戶的適當信息:
主活動.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()
方法來處理退出按鈕:
主活動.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 實例變量:
主活動.kt
// Firebase instance variables
// ...
private lateinit var db: FirebaseDatabase
private lateinit var adapter: FriendlyMessageAdapter
使用下面定義的代碼在註釋// Initialize Realtime Database and FirebaseRecyclerAdapter
下修改 MainActivity 的onCreate()
方法。此代碼添加實時數據庫中的所有現有消息,然後偵聽 Firebase 實時數據庫中messages
路徑下的新子條目。它為每條消息向 UI 添加一個新元素:
主活動.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()
方法:
FriendlyMessageAdapter.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()
方法:
FriendlyMessageAdapter.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()
方法,如下所示:
主活動.kt
public override fun onPause() {
adapter.stopListening()
super.onPause()
}
public override fun onResume() {
super.onResume()
adapter.startListening()
}
測試同步消息
- 單擊運行(
).
- 在 Emulator Suite UI 中,返回實時數據庫選項卡,然後手動添加一條新消息。確認該消息顯示在您的 Android 應用程序中:
恭喜,您剛剛為您的應用程序添加了一個實時數據庫!
8. 發送信息
實現短信發送
在本部分中,您將為應用程序用戶添加發送短信的功能。下面的代碼片段偵聽發送按鈕上的點擊事件,使用消息字段的內容創建一個新的FriendlyMessage
對象,並將消息推送到數據庫。 push()
方法將自動生成的 ID 添加到推送對象的路徑中。這些 ID 是連續的,以確保新消息將添加到列表的末尾。
在MainActivity
類的onCreate()
方法中更新發送按鈕的點擊監聽。這段代碼已經在onCreate()
方法的底部。更新onClick()
主體以匹配以下代碼:
主活動.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
選擇圖像
為了添加圖像,此代碼實驗室使用 Cloud Storage for Firebase。 Cloud Storage 是存儲應用程序二進制數據的好地方。
處理圖像選擇並寫入臨時消息
一旦用戶選擇了圖像,就會啟動圖像選擇Intent
。這已經在onCreate()
方法末尾的代碼中實現了。完成後,它會調用MainActivity
的onImageSelected()
方法。使用下面的代碼片段,您將向數據庫寫入一條帶有臨時圖像 URL 的消息,指示正在上傳圖像。
主活動.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()
中調用以啟動所選圖像的上傳。上傳完成後,您將更新消息以使用適當的圖像。
主活動.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 模擬器中,輸入一條消息,然後點擊發送按鈕。新消息應該在應用程序用戶界面和 Firebase Emulator Suite 用戶界面中可見。
- 在 Android 模擬器中,點擊“+”圖像以從您的設備中選擇一個圖像。新消息應首先顯示為佔位符圖像,然後在圖像上傳完成後顯示為所選圖像。新消息也應該在 Emulator Suite UI 中可見,特別是作為實時數據庫選項卡中的對象和存儲選項卡中的 blob。
9. 恭喜!
您剛剛使用 Firebase 構建了一個實時聊天應用程序!
你學到了什麼
- Firebase 身份驗證
- Firebase 實時數據庫
- 用於 Firebase 的雲存儲
接下來,嘗試使用您在此 Codelab 中學到的知識將 Firebase 添加到您自己的 Android 應用中!要了解有關 Firebase 的更多信息,請訪問firebase.google.com 。
如果您想了解如何設置真實的Firebase 項目並使用真實的Firebase 資源(而不是演示項目和僅模擬資源),請繼續下一步。
注意:即使在您設置了一個真正的 Firebase 項目之後,尤其是當您開始構建一個真正的應用程序時,我們仍然建議您使用 Firebase Local Emulator Suite 進行開發和測試。
10. 可選:創建並設置一個 Firebase 項目
在此步驟中,您將創建一個真正的 Firebase 項目和一個 Firebase Android 應用程序以用於此 Codelab。您還將向您的應用添加特定於應用的 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 。您可能還需要運行Build/Clean Project和Build/Rebuild Project以使配置更改生效。
配置 Firebase 身份驗證
在您的應用程序可以代表您的用戶訪問 Firebase 身份驗證 API 之前,您需要啟用 Firebase 身份驗證和您要在您的應用程序中使用的登錄提供程序。
- 在Firebase 控制台中,從左側導航面板中選擇身份驗證。
- 選擇登錄方法選項卡。
- 單擊Email/Password ,然後將開關切換為已啟用(藍色)。
- 單擊Google ,然後將開關切換為啟用(藍色)並設置項目支持電子郵件。
如果您稍後在此 Codelab 中收到消息“CONFIGURATION_NOT_FOUND”的錯誤,請返回此步驟並仔細檢查您的工作。
配置實時數據庫
此 Codelab 中的應用將聊天消息存儲在 Firebase 實時數據庫中。在本節中,我們將創建一個數據庫並通過稱為 Firebase 安全規則的 JSON 配置語言配置其安全性。
- 在Firebase 控制台中,從左側導航面板中選擇實時數據庫。
- 單擊創建數據庫以創建一個新的實時數據庫實例。出現提示時,選擇
us-central1
區域,然後單擊下一步。 - 當提示有關安全規則時,選擇鎖定模式,然後單擊啟用。
- 創建數據庫實例後,選擇“規則”選項卡,然後使用以下內容更新規則配置:
{ "rules": { "messages": { ".read": "auth.uid != null", ".write": "auth.uid != null" } } }
有關安全規則工作原理的更多信息(包括有關“auth”變量的文檔),請參閱實時數據庫安全文檔。
為 Firebase 配置雲存儲
- 在Firebase 控制台中,從左側導航面板中選擇存儲。
- 單擊開始為您的項目啟用 Cloud Storage。
- 按照對話框中的步驟設置您的存儲桶,使用建議的默認值。
連接到 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
。
一、概述
圖片:Working Friendly Chat 應用程序。
歡迎來到 Friendly Chat 代碼實驗室。在此 Codelab 中,您將學習如何使用 Firebase 平台在 Android 上創建聊天應用。
你會學到什麼
- 如何使用 Firebase 身份驗證允許用戶登錄。
- 如何使用 Firebase 實時數據庫同步數據。
- 如何在 Cloud Storage for Firebase 中存儲二進製文件。
- 如何使用 Firebase Local Emulator Suite 通過 Firebase 開發 Android 應用程序。
你需要什麼
- Android Studio版本 4.2+。
- Android 模擬器Android 5.0+。
- 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
文件的警告,請不要擔心。它將在稍後的步驟中添加。
檢查依賴關係
在此代碼實驗室中,您需要的所有依賴項都已為您添加,但了解如何將 Firebase SDK 添加到您的應用很重要:
構建.gradle
buildscript {
// ...
dependencies {
classpath 'com.android.tools.build:gradle:7.2.2'
// The google-services plugin is required to parse the google-services.json file
classpath 'com.google.gms:google-services:4.3.13'
}
}
應用程序/build.gradle
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.2.0'
// Firebase SDK
implementation platform('com.google.firebase:firebase-bom:30.3.2')
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.1'
implementation 'com.firebaseui:firebase-ui-database:8.0.1'
}
3. 安裝 Firebase CLI
在此 Codelab 中,您將使用Firebase 模擬器套件在本地模擬 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 Emulator Suite。
將mock-google-services.json
文件作為google-services.json
複製到build-android-start/app
文件夾中:
cp mock-google-services.json build-android-start/app/google-services.json
在此 Codelab 的最後一步,您將學習如何創建一個真正的 Firebase 項目和 Firebase Android 應用程序,以便您可以用您自己的配置替換這個模擬 JSON 文件。
運行應用
既然您已將項目導入 Android Studio 並添加了 Firebase 配置 JSON 文件,您就可以首次運行該應用程序了。
- 啟動你的安卓模擬器。
- 在 Android Studio 中,點擊運行(
) 在工具欄中。
該應用程序應在您的 Android 模擬器上啟動。此時,您應該看到一個空的消息列表,發送和接收消息將不起作用。在此 Codelab 的下一步中,您將對用戶進行身份驗證,以便他們可以使用 Friendly Chat。
6.啟用身份驗證
此應用程序將使用 Firebase 實時數據庫來存儲所有聊天消息。不過,在我們添加數據之前,我們應該確保該應用程序是安全的,並且只有經過身份驗證的用戶才能發布消息。在此步驟中,我們將啟用 Firebase 身份驗證並配置實時數據庫安全規則。
添加基本登錄功能
接下來,我們將向應用程序添加一些基本的 Firebase 身份驗證代碼,以檢測用戶並實現登錄屏幕。
檢查當前用戶
首先在MainActivity.kt
類中添加如下實例變量:
主活動.kt
// Firebase instance variables
private lateinit var auth: FirebaseAuth
現在讓我們修改MainActivity
以便在用戶打開應用程序且未通過身份驗證時將用戶發送到登錄屏幕。將binding
附加到視圖後,將以下內容添加到onCreate()
方法:
主活動.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()
期間登錄:
主活動.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 用戶的適當信息:
主活動.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()
方法來處理退出按鈕:
主活動.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 實例變量:
主活動.kt
// Firebase instance variables
// ...
private lateinit var db: FirebaseDatabase
private lateinit var adapter: FriendlyMessageAdapter
使用下面定義的代碼在註釋// Initialize Realtime Database and FirebaseRecyclerAdapter
下修改 MainActivity 的onCreate()
方法。此代碼添加實時數據庫中的所有現有消息,然後偵聽 Firebase 實時數據庫中messages
路徑下的新子條目。它為每條消息向 UI 添加一個新元素:
主活動.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()
方法:
FriendlyMessageAdapter.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()
方法:
FriendlyMessageAdapter.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()
方法,如下所示:
主活動.kt
public override fun onPause() {
adapter.stopListening()
super.onPause()
}
public override fun onResume() {
super.onResume()
adapter.startListening()
}
測試同步消息
- 單擊運行(
).
- 在 Emulator Suite UI 中,返回實時數據庫選項卡,然後手動添加一條新消息。確認該消息顯示在您的 Android 應用程序中:
恭喜,您剛剛為您的應用程序添加了一個實時數據庫!
8. 發送信息
實現短信發送
在本部分中,您將為應用程序用戶添加發送短信的功能。下面的代碼片段偵聽發送按鈕上的點擊事件,使用消息字段的內容創建一個新的FriendlyMessage
對象,並將消息推送到數據庫。 push()
方法將自動生成的 ID 添加到推送對象的路徑中。這些 ID 是連續的,以確保新消息將添加到列表的末尾。
在MainActivity
類的onCreate()
方法中更新發送按鈕的點擊監聽。這段代碼已經在onCreate()
方法的底部。更新onClick()
主體以匹配以下代碼:
主活動.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
選擇圖片
為了添加圖像,此代碼實驗室使用 Cloud Storage for Firebase。 Cloud Storage 是存儲應用程序二進制數據的好地方。
處理圖像選擇並寫入臨時消息
一旦用戶選擇了圖像,就會啟動圖像選擇Intent
。這已經在onCreate()
方法末尾的代碼中實現了。完成後,它會調用MainActivity
的onImageSelected()
方法。使用下面的代碼片段,您將向數據庫寫入一條帶有臨時圖像 URL 的消息,指示正在上傳圖像。
主活動.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()
中調用以啟動所選圖像的上傳。上傳完成後,您將更新消息以使用適當的圖像。
主活動.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 模擬器中,輸入一條消息,然後點擊發送按鈕。新消息應該在應用程序用戶界面和 Firebase Emulator Suite 用戶界面中可見。
- 在 Android 模擬器中,點擊“+”圖像以從您的設備中選擇一個圖像。新消息應首先顯示為佔位符圖像,然後在圖像上傳完成後顯示為所選圖像。新消息也應該在 Emulator Suite UI 中可見,特別是作為實時數據庫選項卡中的對象和存儲選項卡中的 blob。
9. 恭喜!
您剛剛使用 Firebase 構建了一個實時聊天應用程序!
你學到了什麼
- Firebase 身份驗證
- Firebase 實時數據庫
- 用於 Firebase 的雲存儲
接下來,嘗試使用您在此 Codelab 中學到的知識將 Firebase 添加到您自己的 Android 應用中!要了解有關 Firebase 的更多信息,請訪問firebase.google.com 。
如果您想了解如何設置真實的Firebase 項目並使用真實的Firebase 資源(而不是演示項目和僅模擬資源),請繼續下一步。
注意:即使在您設置了一個真正的 Firebase 項目之後,尤其是當您開始構建一個真正的應用程序時,我們仍然建議您使用 Firebase Local Emulator Suite 進行開發和測試。
10. 可選:創建並設置一個 Firebase 項目
在此步驟中,您將創建一個真正的 Firebase 項目和一個 Firebase Android 應用程序以用於此 Codelab。您還將向您的應用添加特定於應用的 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
目錄中。 - Skip the next steps shown in the console's setup workflow (they've already been done for you in the
build-android-start
project). - Make sure that all dependencies are available to your app by syncing your project with Gradle files. From the Android Studio toolbar, select File > Sync Project with Gradle Files . You may also need to run Build/Clean Project and Build/Rebuild Project for the config changes to take place.
Configure Firebase Authentication
Before your app can access the Firebase Authentication APIs on behalf of your users, you need to enable Firebase Authentication and the sign-in providers you want to use in your app.
- In the Firebase console , select Authentication from the left-side navigation panel.
- Select the Sign-in method tab.
- Click Email/Password , then toggle the switch to enabled (blue).
- Click Google , then toggle the switch to enabled (blue) and set a project support email.
If you get errors later in this codelab with the message "CONFIGURATION_NOT_FOUND", come back to this step and double check your work.
Configure Realtime Database
The app in this codelab stores chat messages in Firebase Realtime Database. In this section, we'll create a database and configure its security via a JSON configuration language called Firebase Security Rules.
- In the Firebase console , select Realtime Database from the left-side navigation panel.
- Click Create Database to create a new Realtime Database instance. When prompted, select the
us-central1
region, then click Next . - When prompted about security rules, choose locked mode , then click Enable .
- Once the database instance has been created, select the Rules tab, then update the rules configuration with the following:
{ "rules": { "messages": { ".read": "auth.uid != null", ".write": "auth.uid != null" } } }
For more information on how Security Rules work (including documentation on the "auth" variable), see the Realtime Database security documentation .
Configure Cloud Storage for Firebase
- In the Firebase console , select Storage from the left-side navigation panel.
- Click Get Started to enable Cloud Storage for your project.
- Follow the steps in the dialog to set up your bucket, using the suggested defaults.
Connect to Firebase resources
In an earlier step of this codelab, you added the following to MainActivity.kt
. This conditional block connected your Android project to the 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)
}
If you want to connect your app to your new real Firebase project and its real Firebase resources, you can either remove this block or run your app in release mode so that BuildConfig.DEBUG
is false
.