### Cloud Storage Operations in Kotlin Source: https://context7.com/firebase/snippets-android/llms.txt Comprehensive examples for uploading, downloading, managing, and listing files in Firebase Cloud Storage. ```kotlin import com.google.firebase.storage.storage import com.google.firebase.storage.storageMetadata import com.google.firebase.Firebase val storage = Firebase.storage val storageRef = storage.reference // Create references val mountainsRef = storageRef.child("mountains.jpg") val mountainImagesRef = storageRef.child("images/mountains.jpg") // Upload from memory (byte array) val bitmap = (imageView.drawable as BitmapDrawable).bitmap val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val data = baos.toByteArray() mountainsRef.putBytes(data) .addOnFailureListener { /* Handle unsuccessful uploads */ } .addOnSuccessListener { taskSnapshot -> // taskSnapshot.metadata contains file metadata } // Upload from file with metadata val file = Uri.fromFile(File("path/to/mountains.jpg")) val metadata = storageMetadata { contentType = "image/jpeg" } val uploadTask = storageRef.child("images/${file.lastPathSegment}").putFile(file, metadata) // Monitor upload progress uploadTask.addOnProgressListener { (bytesTransferred, totalByteCount) -> val progress = (100.0 * bytesTransferred) / totalByteCount Log.d(TAG, "Upload is $progress% done") }.addOnPausedListener { Log.d(TAG, "Upload is paused") }.addOnFailureListener { // Handle unsuccessful uploads }.addOnSuccessListener { // Handle successful uploads } // Manage uploads uploadTask.pause() uploadTask.resume() uploadTask.cancel() // Get download URL after upload val ref = storageRef.child("images/mountains.jpg") val urlTask = ref.putFile(file).continueWithTask { task -> if (!task.isSuccessful) { task.exception?.let { throw it } } ref.downloadUrl }.addOnCompleteListener { task -> if (task.isSuccessful) { val downloadUri = task.result } } // Download to memory val ONE_MEGABYTE: Long = 1024 * 1024 storageRef.child("images/island.jpg").getBytes(ONE_MEGABYTE) .addOnSuccessListener { /* Data returned */ } .addOnFailureListener { /* Handle errors */ } // Download to local file val localFile = File.createTempFile("images", "jpg") storageRef.child("images/island.jpg").getFile(localFile) .addOnSuccessListener { /* File created */ } .addOnFailureListener { /* Handle errors */ } // Delete file storageRef.child("images/desert.jpg").delete() .addOnSuccessListener { /* File deleted */ } .addOnFailureListener { /* Error occurred */ } // List all files in a directory val listRef = storage.reference.child("files/uid") listRef.listAll() .addOnSuccessListener { (items, prefixes) -> for (prefix in prefixes) { /* Subdirectories */ } for (item in items) { /* Files */ } } ``` -------------------------------- ### Initialize Firebase Analytics Source: https://context7.com/firebase/snippets-android/llms.txt Get an instance of Firebase Analytics. This is the entry point for all analytics logging operations. Ensure Firebase is initialized in your application. ```kotlin import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import com.google.firebase.Firebase // Initialize Analytics val firebaseAnalytics = Firebase.analytics ``` -------------------------------- ### Get Remote Config Values Source: https://context7.com/firebase/snippets-android/llms.txt Retrieve configuration values from Firebase Remote Config after they have been fetched and activated. This example shows how to get a string value. ```kotlin import com.google.firebase.remoteconfig.remoteConfig import com.google.firebase.remoteconfig.get // Get config values val welcomeMessage = remoteConfig[WELCOME_MESSAGE_KEY].asString() ``` -------------------------------- ### Set User Property for Analytics Source: https://context7.com/firebase/snippets-android/llms.txt Set a custom user property to segment your users based on attributes. For example, 'favorite_food' or 'user_level'. ```kotlin import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import com.google.firebase.Firebase // Set user property firebaseAnalytics.setUserProperty("favorite_food", "pizza") ``` -------------------------------- ### Get FCM Registration Token Source: https://context7.com/firebase/snippets-android/llms.txt Retrieve the FCM registration token for the current device. This token is used to identify the device for sending targeted messages. Ensure Firebase is initialized. ```kotlin import com.google.firebase.messaging.messaging import com.google.firebase.messaging.remoteMessage import com.google.firebase.Firebase // Get FCM registration token Firebase.messaging.getToken().addOnCompleteListener { task -> if (!task.isSuccessful) { Log.w(TAG, "Fetching FCM registration token failed", task.exception) return@addOnCompleteListener } val token = task.result Log.d(TAG, "FCM Registration token: $token") } ``` -------------------------------- ### Build Project Locally Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Run the build process to ensure all tests pass. ```shell gulp ``` -------------------------------- ### Implement Phone Authentication Source: https://context7.com/firebase/snippets-android/llms.txt Configure phone authentication options and handle verification callbacks for SMS-based sign-in. ```kotlin import com.google.firebase.auth.PhoneAuthOptions import com.google.firebase.auth.PhoneAuthProvider import java.util.concurrent.TimeUnit val phoneNumber = "+16505554567" val smsCode = "123456" val firebaseAuth = Firebase.auth val firebaseAuthSettings = firebaseAuth.firebaseAuthSettings // Configure auto-retrieval for testing firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode) val options = PhoneAuthOptions.newBuilder(firebaseAuth) .setPhoneNumber(phoneNumber) .setTimeout(60L, TimeUnit.SECONDS) .setActivity(this) .setCallbacks(object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(credential: PhoneAuthCredential) { // Instant verification is applied and a credential is directly returned firebaseAuth.signInWithCredential(credential) } override fun onCodeSent( verificationId: String, forceResendingToken: PhoneAuthProvider.ForceResendingToken, ) { // Save the verification id for later use } override fun onVerificationFailed(e: FirebaseException) { // Handle verification failure } }) .build() PhoneAuthProvider.verifyPhoneNumber(options) ``` -------------------------------- ### Manage Realtime Database Operations Source: https://context7.com/firebase/snippets-android/llms.txt Covers initializing database references, writing data, implementing fan-out updates, reading with listeners, and performing atomic increments. ```kotlin import com.google.firebase.database.database import com.google.firebase.database.getValue import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.ValueEventListener import com.google.firebase.database.ServerValue // Initialize database reference val database = Firebase.database.reference // Data class for users data class User(val name: String = "", val email: String = "") // Write data fun writeNewUser(userId: String, name: String, email: String) { val user = User(name, email) database.child("users").child(userId).setValue(user) .addOnSuccessListener { /* Write was successful! */ } .addOnFailureListener { /* Write failed */ } } // Fan-out pattern for multi-path updates fun writeNewPost(userId: String, username: String, title: String, body: String) { val key = database.child("posts").push().key ?: return val post = Post(userId, username, title, body) val postValues = post.toMap() val childUpdates = hashMapOf( "/posts/$key" to postValues, "/user-posts/$userId/$key" to postValues, ) database.updateChildren(childUpdates) } // Read data with listener val postListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { val post = dataSnapshot.getValue() // Use post data } override fun onCancelled(databaseError: DatabaseError) { Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) } } postReference.addValueEventListener(postListener) // Atomic increment with ServerValue fun onStarClicked(uid: String, key: String) { val updates: MutableMap = hashMapOf( "posts/$key/stars/$uid" to true, "posts/$key/starCount" to ServerValue.increment(1), "user-posts/$uid/$key/stars/$uid" to true, "user-posts/$uid/$key/starCount" to ServerValue.increment(1), ) database.updateChildren(updates) } ``` -------------------------------- ### Implement Cloud Functions in Kotlin Source: https://context7.com/firebase/snippets-android/llms.txt Initialize functions, connect to the emulator, call HTTPS functions, handle errors, and stream responses. ```kotlin import com.google.firebase.functions.functions import com.google.firebase.functions.FirebaseFunctionsException import com.google.firebase.Firebase // Initialize Functions val functions = Firebase.functions // Connect to emulator for development functions.useEmulator("10.0.2.2", 5001) // Call a callable function private fun addMessage(text: String): Task { val data = hashMapOf( "text" to text, "push" to true, ) return functions .getHttpsCallable("addMessage") .call(data) .continueWith { task -> val result = task.result?.data as String result } } // Handle function errors addMessage(inputMessage) .addOnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details } } } // Streaming function calls val getForecast = functions.getHttpsCallable("getForecast") getForecast.stream( mapOf("locations" to favoriteLocations) ).asFlow().collect { response -> when (response) { is StreamResponse.Message -> { val forecastDataChunk = response.message.data as Map updateUI( forecastDataChunk["latitude"] as Double, forecastDataChunk["longitude"] as Double, forecastDataChunk["forecast"] as Double, ) } is StreamResponse.Result -> { val allWeatherForecasts = response.result.data as List> finalizeUI(allWeatherForecasts) } } } ``` -------------------------------- ### Implement Performance Monitoring in Kotlin Source: https://context7.com/firebase/snippets-android/llms.txt Use trace annotations, manual traces with custom metrics, attributes, and HTTP metrics to monitor app performance. ```kotlin import com.google.firebase.perf.performance import com.google.firebase.perf.trace import com.google.firebase.perf.metrics.AddTrace import com.google.firebase.Firebase // Add trace annotation to methods @AddTrace(name = "onCreateTrace", enabled = true) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } // Manual trace with custom metrics val myTrace = Firebase.performance.newTrace("test_trace") myTrace.start() val item = cache.fetch("item") if (item != null) { myTrace.incrementMetric("item_cache_hit", 1) } else { myTrace.incrementMetric("item_cache_miss", 1) } myTrace.stop() // Trace with custom attributes using Kotlin DSL Firebase.performance.newTrace("test_trace").trace { putAttribute("experiment", "A") val experimentValue = getAttribute("experiment") removeAttribute("experiment") val traceAttributes = this.attributes } // Manual HTTP metric val url = URL("https://www.google.com") val metric = Firebase.performance.newHttpMetric( "https://www.google.com", FirebasePerformance.HttpMethod.GET, ) metric.trace { val conn = url.openConnection() as HttpURLConnection conn.doOutput = true setRequestPayloadSize(data.size.toLong()) setHttpResponseCode(conn.responseCode) conn.disconnect() } // Enable/disable collection based on Remote Config Firebase.performance.isPerformanceCollectionEnabled = !config.getBoolean("perf_disable") ``` -------------------------------- ### Initialize Generative Model with Firebase AI Source: https://context7.com/firebase/snippets-android/llms.txt Initializes a generative model using Firebase AI with Google AI backend. Configure system instructions for model behavior. ```kotlin import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend import com.google.firebase.ai.type.content import com.google.firebase.Firebase // Initialize generative model val model = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel( modelName = "gemini-2.5-flash", systemInstruction = content { text("You are a cat. Your name is Neko.") } ) ``` -------------------------------- ### Documentation Issue Template Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Use this template when reporting missing or unclear documentation. ```text What are you trying to do or find out more about? Where have you looked? Where did you expect to find this information? ``` -------------------------------- ### Execute Firestore Queries and Real-time Listeners Source: https://context7.com/firebase/snippets-android/llms.txt Covers filtering, ordering, pagination, and real-time synchronization using snapshot listeners for documents and collections. ```kotlin import com.google.firebase.firestore.Query import com.google.firebase.firestore.Filter import com.google.firebase.firestore.DocumentChange val citiesRef = db.collection("cities") // Simple queries val stateQuery = citiesRef.whereEqualTo("state", "CA") val populationQuery = citiesRef.whereLessThan("population", 100000) val nameQuery = citiesRef.whereGreaterThanOrEqualTo("name", "San Francisco") // Compound queries with AND/OR filters val query = citiesRef.where(Filter.and( Filter.equalTo("state", "CA"), Filter.or( Filter.equalTo("capital", true), Filter.greaterThanOrEqualTo("population", 1000000) ) )) // Array contains and in queries citiesRef.whereArrayContains("regions", "west_coast") citiesRef.whereIn("country", listOf("USA", "Japan")) citiesRef.whereArrayContainsAny("regions", listOf("west_coast", "east_coast")) // Order and limit results citiesRef.orderBy("name").limit(3) citiesRef.orderBy("name", Query.Direction.DESCENDING).limit(3) citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2) // Pagination with startAfter val first = db.collection("cities").orderBy("population").limit(25) first.get().addOnSuccessListener { documentSnapshots -> val lastVisible = documentSnapshots.documents[documentSnapshots.size() - 1] val next = db.collection("cities") .orderBy("population") .startAfter(lastVisible) .limit(25) } // Real-time listener for document val docRef = db.collection("cities").document("SF") docRef.addSnapshotListener { snapshot, e -> if (e != null) { Log.w(TAG, "Listen failed.", e) return@addSnapshotListener } if (snapshot != null && snapshot.exists()) { Log.d(TAG, "Current data: ${snapshot.data}") } } // Listen for collection changes with diff tracking db.collection("cities") .whereEqualTo("state", "CA") .addSnapshotListener { snapshots, e -> for (dc in snapshots!!.documentChanges) { when (dc.type) { DocumentChange.Type.ADDED -> Log.d(TAG, "New city: ${dc.document.data}") DocumentChange.Type.MODIFIED -> Log.d(TAG, "Modified city: ${dc.document.data}") DocumentChange.Type.REMOVED -> Log.d(TAG, "Removed city: ${dc.document.data}") } } } ``` -------------------------------- ### Initialize Mobile Ads SDK Source: https://context7.com/firebase/snippets-android/llms.txt Initializes the Google Mobile Ads SDK. This should be called once at the beginning of your app's lifecycle, typically in the main Activity's onCreate method. ```kotlin import com.google.android.gms.ads.MobileAds // Initialize Mobile Ads SDK override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MobileAds.initialize(this) } ``` -------------------------------- ### Configure Generation Parameters for Gemini Model Source: https://context7.com/firebase/snippets-android/llms.txt Configures generation parameters like candidate count, max output tokens, stop sequences, temperature, topK, and topP for a Gemini model. ```kotlin import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend import com.google.firebase.ai.type.generationConfig import com.google.firebase.Firebase // Configure generation parameters val config = generationConfig { candidateCount = 1 maxOutputTokens = 200 stopSequences = listOf("red") temperature = 0.9f topK = 16 topP = 0.1f } val configuredModel = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel(modelName = "gemini-2.5-flash", generationConfig = config) ``` -------------------------------- ### Listen for Real-time Remote Config Updates Source: https://context7.com/firebase/snippets-android/llms.txt Implement a listener to receive real-time updates for configuration changes. This allows your app to react to changes without requiring a full fetch. ```kotlin import com.google.firebase.remoteconfig.remoteConfig import com.google.firebase.remoteconfig.ConfigUpdate import com.google.firebase.remoteconfig.ConfigUpdateListener import com.google.firebase.remoteconfig.FirebaseRemoteConfigException // Listen for real-time config updates remoteConfig.addOnConfigUpdateListener(object : ConfigUpdateListener { override fun onUpdate(configUpdate: ConfigUpdate) { Log.d(TAG, "Updated keys: " + configUpdate.updatedKeys) if (configUpdate.updatedKeys.contains("welcome_message")) { remoteConfig.activate().addOnCompleteListener { displayWelcomeMessage() } } } override fun onError(error: FirebaseRemoteConfigException) { Log.w(TAG, "Config update error with code: " + error.code, error) } }) ``` -------------------------------- ### Configure and Fetch Remote Config Source: https://context7.com/firebase/snippets-android/llms.txt Initialize and configure Firebase Remote Config, including setting fetch intervals and default values. Fetch and activate configuration parameters. ```kotlin import com.google.firebase.remoteconfig.remoteConfig import com.google.firebase.remoteconfig.remoteConfigSettings import com.google.firebase.remoteconfig.get import com.google.firebase.remoteconfig.ConfigUpdate import com.google.firebase.remoteconfig.ConfigUpdateListener import com.google.firebase.Firebase // Get Remote Config instance val remoteConfig = Firebase.remoteConfig // Configure settings val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 3600 } remoteConfig.setConfigSettingsAsync(configSettings) // Set default values from XML resource remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults) // Fetch and activate config remoteConfig.fetchAndActivate() .addOnCompleteListener(this) { task -> if (task.isSuccessful) { val updated = task.result Log.d(TAG, "Config params updated: $updated") } else { Log.d(TAG, "Fetch failed") } displayWelcomeMessage() } ``` -------------------------------- ### Configure Safety Settings for Gemini Model Source: https://context7.com/firebase/snippets-android/llms.txt Sets up safety settings for a generative model, specifying thresholds for categories like harassment and hate speech. ```kotlin import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend import com.google.firebase.ai.type.SafetySetting import com.google.firebase.ai.type.HarmCategory import com.google.firebase.ai.type.HarmBlockThreshold import com.google.firebase.Firebase // Configure safety settings val harassmentSafety = SafetySetting(HarmCategory.HARASSMENT, HarmBlockThreshold.ONLY_HIGH) val hateSpeechSafety = SafetySetting(HarmCategory.HATE_SPEECH, HarmBlockThreshold.MEDIUM_AND_ABOVE) val safeModel = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel( modelName = "gemini-2.5-flash", safetySettings = listOf(harassmentSafety, hateSpeechSafety) ) ``` -------------------------------- ### Perform CRUD Operations on Firestore Documents Source: https://context7.com/firebase/snippets-android/llms.txt Demonstrates adding, setting, retrieving, updating, and deleting documents in a Firestore collection using Kotlin. ```kotlin import com.google.firebase.firestore.firestore import com.google.firebase.Firebase val db = Firebase.firestore // Data class for type-safe operations data class City( val name: String? = null, val state: String? = null, val country: String? = null, @field:JvmField val isCapital: Boolean? = null, val population: Long? = null, val regions: List? = null, ) // Add document with generated ID val user = hashMapOf( "first" to "Ada", "last" to "Lovelace", "born" to 1815, ) db.collection("users") .add(user) .addOnSuccessListener { documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}") } .addOnFailureListener { e -> Log.w(TAG, "Error adding document", e) } // Set document with specific ID val city = hashMapOf( "name" to "Los Angeles", "state" to "CA", "country" to "USA", ) db.collection("cities").document("LA") .set(city) .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") } .addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) } // Get a document val docRef = db.collection("cities").document("SF") docRef.get() .addOnSuccessListener { document -> if (document != null) { Log.d(TAG, "DocumentSnapshot data: ${document.data}") } else { Log.d(TAG, "No such document") } } .addOnFailureListener { exception -> Log.d(TAG, "get failed with ", exception) } // Update document val washingtonRef = db.collection("cities").document("DC") washingtonRef.update("capital", true) .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!") } .addOnFailureListener { e -> Log.w(TAG, "Error updating document", e) } // Delete document db.collection("cities").document("DC") .delete() .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") } .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) } ``` -------------------------------- ### Perform Multi-Turn Chat with Gemini Model Source: https://context7.com/firebase/snippets-android/llms.txt Initiates a multi-turn chat with a generative model, providing initial history and sending a new message. Prints the text response. ```kotlin import com.google.firebase.ai.type.content // Multi-turn chat (non-streaming) val chat = generativeModel.startChat( history = listOf( content(role = "user") { text("Hello, I have 2 dogs in my house.") }, content(role = "model") { text("Great to meet you. What would you like to know?") } ) ) val response = chat.sendMessage("How many paws are in my house?") print(response.text) ``` -------------------------------- ### Switch to master branch Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Forces a checkout of the master branch. ```shell git checkout master -f ``` -------------------------------- ### Configure Gemini Model for Function Calling Source: https://context7.com/firebase/snippets-android/llms.txt Configures a generative model to use function calling by providing a list of tool definitions, including function declarations. ```kotlin import com.google.firebase.ai.ai import com.google.firebase.ai.type.GenerativeBackend import com.google.firebase.ai.type.Tool import com.google.firebase.Firebase val functionModel = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel( modelName = "gemini-2.5-flash", tools = listOf(Tool.functionDeclarations(listOf(fetchWeatherTool))) ) ``` -------------------------------- ### Git Branch Creation Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Create a new branch from the master branch for your changes. ```shell git checkout -b my-fix-branch master ``` -------------------------------- ### Push Branch to GitHub Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Push your local branch to the remote repository. ```shell git push origin my-fix-branch ``` -------------------------------- ### Perform Firestore Transactions and Aggregations Source: https://context7.com/firebase/snippets-android/llms.txt Demonstrates atomic read-write transactions, batch operations, array updates, and server-side aggregate queries in Cloud Firestore. ```kotlin import com.google.firebase.firestore.AggregateField import com.google.firebase.firestore.AggregateSource import com.google.firebase.firestore.FieldValue // Transaction for atomic read-write operations val sfDocRef = db.collection("cities").document("SF") db.runTransaction { transaction -> val snapshot = transaction.get(sfDocRef) val newPopulation = snapshot.getDouble("population")!! + 1 if (newPopulation <= 1000000) { transaction.update(sfDocRef, "population", newPopulation) newPopulation } else { throw FirebaseFirestoreException( "Population too high", FirebaseFirestoreException.Code.ABORTED, ) } }.addOnSuccessListener { result -> Log.d(TAG, "Transaction success: $result") }.addOnFailureListener { e -> Log.w(TAG, "Transaction failure.", e) } // Batch writes for multiple operations val nycRef = db.collection("cities").document("NYC") val sfRef = db.collection("cities").document("SF") val laRef = db.collection("cities").document("LA") db.runBatch { batch -> batch.set(nycRef, City()) batch.update(sfRef, "population", 1000000L) batch.delete(laRef) }.addOnCompleteListener { } // Atomic array updates val washingtonRef = db.collection("cities").document("DC") washingtonRef.update("regions", FieldValue.arrayUnion("greater_virginia")) washingtonRef.update("regions", FieldValue.arrayRemove("east_coast")) // Atomic increment washingtonRef.update("population", FieldValue.increment(50)) // Count aggregation val query = db.collection("cities") query.count().get(AggregateSource.SERVER).addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Count: ${task.result.count}") } } // Multiple aggregations (count, sum, average) val aggregateQuery = query.aggregate( AggregateField.count(), AggregateField.sum("population"), AggregateField.average("population") ) aggregateQuery.get(AggregateSource.SERVER).addOnCompleteListener { task -> if (task.isSuccessful) { val snapshot = task.result Log.d(TAG, "Count: ${snapshot.get(AggregateField.count())}") Log.d(TAG, "Sum: ${snapshot.get(AggregateField.sum("population"))}") Log.d(TAG, "Average: ${snapshot.get(AggregateField.average("population"))}") } } ``` -------------------------------- ### Log Analytics Screen View Source: https://context7.com/firebase/snippets-android/llms.txt Log a screen view event to track which screens users are visiting in your app. Requires `SCREEN_NAME` and `SCREEN_CLASS` parameters. ```kotlin import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import com.google.firebase.Firebase // Log screen view firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW) { param(FirebaseAnalytics.Param.SCREEN_NAME, "Home Page") param(FirebaseAnalytics.Param.SCREEN_CLASS, "MainActivity") } ``` -------------------------------- ### Bug Report Template Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Use this template when submitting a bug report to provide necessary system and reproduction details. ```text System information (OS, Device, etc): What steps will reproduce the problem: 1. 2. 3. What is the expected result? What happens instead of that? Code, logs, or screenshot that illustrate the problem: ``` -------------------------------- ### Log Ad Impression Event Source: https://context7.com/firebase/snippets-android/llms.txt Log an ad impression event to track ad performance. Include details like ad platform, unit name, format, value, and currency. ```kotlin import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import com.google.firebase.Firebase // Log ad impression firebaseAnalytics.logEvent(FirebaseAnalytics.Event.AD_IMPRESSION) { param(FirebaseAnalytics.Param.AD_PLATFORM, "appLovin") param(FirebaseAnalytics.Param.AD_UNIT_NAME, "banner_ad_unit") param(FirebaseAnalytics.Param.AD_FORMAT, "banner") param(FirebaseAnalytics.Param.VALUE, 0.01) param(FirebaseAnalytics.Param.CURRENCY, "USD") } ``` -------------------------------- ### Rebase and Force Push Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Update your pull request by rebasing against master and force pushing. ```shell git rebase master -i git push origin my-fix-branch -f ``` -------------------------------- ### Implement App Check in Kotlin Source: https://context7.com/firebase/snippets-android/llms.txt Initialize Firebase App Check using Play Integrity for production or the debug provider for development environments. ```kotlin import com.google.firebase.appcheck.appCheck import com.google.firebase.appcheck.playintegrity.PlayIntegrityAppCheckProviderFactory import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory import com.google.firebase.Firebase import com.google.firebase.initialize // Initialize with Play Integrity for production Firebase.initialize(context = this) Firebase.appCheck.installAppCheckProviderFactory( PlayIntegrityAppCheckProviderFactory.getInstance(), ) // Initialize with debug provider for development Firebase.initialize(context = this) Firebase.appCheck.installAppCheckProviderFactory( DebugAppCheckProviderFactory.getInstance(), ) ``` -------------------------------- ### Manage Firebase Authentication State and Profile Source: https://context7.com/firebase/snippets-android/llms.txt Use these methods to check the current user's status, update profile information, reset passwords, and handle re-authentication. ```kotlin import com.google.firebase.auth.auth import com.google.firebase.auth.EmailAuthProvider import com.google.firebase.auth.userProfileChangeRequest import com.google.firebase.Firebase // Check current user authentication state val user = Firebase.auth.currentUser if (user != null) { // User is signed in - get profile info val name = user.displayName val email = user.email val photoUrl = user.photoUrl val emailVerified = user.isEmailVerified val uid = user.uid } else { // No user is signed in } // Update user profile val profileUpdates = userProfileChangeRequest { displayName = "Jane Q. User" photoUri = Uri.parse("https://example.com/jane-q-user/profile.jpg") } user!!.updateProfile(profileUpdates) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "User profile updated.") } } // Send password reset email Firebase.auth.sendPasswordResetEmail("user@example.com") .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Email sent.") } } // Re-authenticate user for sensitive operations val credential = EmailAuthProvider.getCredential("user@example.com", "password1234") user.reauthenticate(credential) .addOnCompleteListener { Log.d(TAG, "User re-authenticated.") } // Sign out Firebase.auth.signOut() ``` -------------------------------- ### Log E-commerce Purchase Event Source: https://context7.com/firebase/snippets-android/llms.txt Log a purchase event with detailed e-commerce information, including transaction details, items, and shipping costs. Requires `FirebaseAnalytics.Param.ITEMS` to be an array of item bundles. ```kotlin import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import com.google.firebase.Firebase // E-commerce: Create item bundles val itemJeggings = Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, "SKU_123") putString(FirebaseAnalytics.Param.ITEM_NAME, "jeggings") putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "pants") putString(FirebaseAnalytics.Param.ITEM_BRAND, "Google") putDouble(FirebaseAnalytics.Param.PRICE, 9.99) } // Log purchase event firebaseAnalytics.logEvent(FirebaseAnalytics.Event.PURCHASE) { param(FirebaseAnalytics.Param.TRANSACTION_ID, "T12345") param(FirebaseAnalytics.Param.AFFILIATION, "Google Store") param(FirebaseAnalytics.Param.CURRENCY, "USD") param(FirebaseAnalytics.Param.VALUE, 14.98) param(FirebaseAnalytics.Param.TAX, 2.58) param(FirebaseAnalytics.Param.SHIPPING, 5.34) param(FirebaseAnalytics.Param.COUPON, "SUMMER_FUN") param(FirebaseAnalytics.Param.ITEMS, arrayOf(itemJeggings)) } ``` -------------------------------- ### Set Custom Keys for Crashlytics Source: https://context7.com/firebase/snippets-android/llms.txt Use this to set custom key-value pairs for crash reports to provide additional context. Keys can be updated during a user's session. ```kotlin import com.google.firebase.crashlytics.crashlytics import com.google.firebase.crashlytics.recordException import com.google.firebase.crashlytics.setCustomKeys import com.google.firebase.Firebase val crashlytics = Firebase.crashlytics // Set custom keys for crash context crashlytics.setCustomKeys { key("my_string_key", "foo") key("my_bool_key", true) key("my_double_key", 1.0) key("my_float_key", 1.0f) key("my_int_key", 1) } // Update keys during user session crashlytics.setCustomKeys { key("current_level", 3) key("last_UI_action", "logged_in") } ``` -------------------------------- ### Stream Chat Response from Gemini Model Source: https://context7.com/firebase/snippets-android/llms.txt Sends a message to a generative model and collects the streaming response chunk by chunk, printing the text of each chunk. ```kotlin chat.sendMessageStream("How many paws are in my house?").collect { chunk -> print(chunk.text) } ``` -------------------------------- ### Enable FCM Auto-Initialization Source: https://context7.com/firebase/snippets-android/llms.txt Enable or disable automatic initialization of FCM. By default, FCM is auto-initialized. This can be controlled at runtime. ```kotlin import com.google.firebase.messaging.messaging import com.google.firebase.messaging.remoteMessage import com.google.firebase.Firebase // Enable auto-init at runtime Firebase.messaging.isAutoInitEnabled = true ``` -------------------------------- ### Git Commit Changes Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Commit changes with a descriptive message. ```shell git commit -a ``` -------------------------------- ### Subscribe to FCM Topic Source: https://context7.com/firebase/snippets-android/llms.txt Subscribe the device to a specific FCM topic to receive broadcast messages. This is useful for sending messages to groups of users, like weather updates. ```kotlin import com.google.firebase.messaging.messaging import com.google.firebase.messaging.remoteMessage import com.google.firebase.Firebase // Subscribe to topic Firebase.messaging.subscribeToTopic("weather") .addOnCompleteListener { task -> var msg = if (task.isSuccessful) "Subscribed" else "Subscribe failed" Log.d(TAG, msg) } ``` -------------------------------- ### Define Function Declaration for Gemini Function Calling Source: https://context7.com/firebase/snippets-android/llms.txt Defines a function declaration for Gemini's function calling capability, specifying the function name, description, and parameters with their schemas. ```kotlin import com.google.firebase.ai.type.FunctionDeclaration import com.google.firebase.ai.type.Schema import com.google.firebase.ai.type.Tool val fetchWeatherTool = FunctionDeclaration( "fetchWeather", "Get the weather conditions for a specific city on a specific date.", mapOf( "location" to Schema.obj( mapOf( "city" to Schema.string("The city of the location."), "state" to Schema.string("The US state of the location.") ), description = "The name of the city and its state for which to get the weather." ), "date" to Schema.string("The date for which to get the weather. Format: YYYY-MM-DD.") ) ) ``` -------------------------------- ### Log Custom Analytics Event Source: https://context7.com/firebase/snippets-android/llms.txt Log a custom event with associated parameters. Use this to track specific user actions or occurrences within your app that are not covered by predefined events. ```kotlin import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.analytics import com.google.firebase.analytics.logEvent import com.google.firebase.Firebase // Log custom event firebaseAnalytics.logEvent("share_image") { param("image_name", "customImage") param("full_text", "I'd love to hear more about this image") } ``` -------------------------------- ### Log Messages and User ID for Crashlytics Source: https://context7.com/firebase/snippets-android/llms.txt Log custom messages and set a user identifier to aid in debugging crashes. These are associated with subsequent crash reports. ```kotlin import com.google.firebase.crashlytics.crashlytics import com.google.firebase.Firebase // Log messages for crash reports Firebase.crashlytics.log("User clicked checkout button") // Set user identifier Firebase.crashlytics.setUserId("user123456789") ``` -------------------------------- ### Request Notification Permission (Android 13+) Source: https://context7.com/firebase/snippets-android/llms.txt Request the POST_NOTIFICATIONS permission for Android 13 (API 33) and above. This is required for FCM to display notifications on newer Android versions. Ensure you have a `requestPermissionLauncher` set up. ```kotlin import com.google.firebase.messaging.messaging import com.google.firebase.messaging.remoteMessage import com.google.firebase.Firebase // Request notification permission (Android 13+) private fun askNotificationPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) { // FCM SDK can post notifications } else { requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) } } } ``` -------------------------------- ### Record Exceptions with Crashlytics Source: https://context7.com/firebase/snippets-android/llms.txt Record caught exceptions to Firebase Crashlytics. You can optionally attach custom keys to the recorded exception for more detailed context. ```kotlin import com.google.firebase.crashlytics.crashlytics import com.google.firebase.crashlytics.recordException import com.google.firebase.Firebase // Record caught exceptions try { methodThatThrows() } catch (e: Exception) { Firebase.crashlytics.recordException(e) } // Record exception with custom keys try { methodThatThrows() } catch (e: Exception) { Firebase.crashlytics.recordException(e) { key("string key", "string value") key("boolean key", true) key("float key", Float.MAX_VALUE) } } ``` -------------------------------- ### Enable/Disable Crashlytics Collection Source: https://context7.com/firebase/snippets-android/llms.txt Control whether Crashlytics collection is enabled or disabled at runtime. This is useful for respecting user privacy settings. ```kotlin import com.google.firebase.crashlytics.crashlytics import com.google.firebase.Firebase // Enable/disable collection at runtime Firebase.crashlytics.setCrashlyticsCollectionEnabled(true) ``` -------------------------------- ### Store FCM Token in Firestore Source: https://context7.com/firebase/snippets-android/llms.txt Asynchronously retrieve the FCM token and store it in Firestore along with a server timestamp. This is a common pattern for managing user-specific FCM tokens. ```kotlin import com.google.firebase.messaging.messaging import com.google.firebase.messaging.remoteMessage import com.google.firebase.Firebase // Store token in Firestore private suspend fun getAndStoreRegToken(): String { val token = Firebase.messaging.token.await() val deviceToken = hashMapOf( "token" to token, "timestamp" to FieldValue.serverTimestamp(), ) Firebase.firestore.collection("fcmTokens").document("myuserid") .set(deviceToken).await() return token } ``` -------------------------------- ### Update master branch Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Pulls the latest changes from the upstream master branch using a fast-forward merge. ```shell git pull --ff upstream master ``` -------------------------------- ### Delete local branch Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Deletes the specified local branch. ```shell git branch -D my-fix-branch ``` -------------------------------- ### Send Upstream FCM Message Source: https://context7.com/firebase/snippets-android/llms.txt Send an upstream message from the client app to your server via FCM. Requires a sender ID and message ID. This is typically used for device-to-cloud communication. ```kotlin import com.google.firebase.messaging.messaging import com.google.firebase.messaging.remoteMessage import com.google.firebase.Firebase // Send upstream message val SENDER_ID = "YOUR_SENDER_ID" val messageId = 0 Firebase.messaging.send( remoteMessage("$SENDER_ID@fcm.googleapis.com") { setMessageId(messageId.toString()) addData("my_message", "Hello World") addData("my_action", "SAY_HELLO") }, ) ``` -------------------------------- ### Delete remote branch Source: https://github.com/firebase/snippets-android/blob/master/CONTRIBUTING.md Removes the specified branch from the remote repository. ```shell git push origin --delete my-fix-branch ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.