Android Firebase Integration Guide - Analytics, FCM Push, and Dynamic Links
Firebase provides a comprehensive suite of tools for Android development. This guide covers essential Firebase services: Analytics, Cloud Messaging (FCM), and Dynamic Links.
Table of Contents
Setup
Add Firebase to Your Project
- Add the Firebase project in the Firebase Console
- Download
google-services.jsonand place it in your app module - Add dependencies:
// Project-level build.gradle
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.3.15'
}
}
// App-level build.gradle
plugins {
id 'com.google.gms.google-services'
}
dependencies {
implementation platform('com.google.firebase:firebase-bom:32.0.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-messaging-ktx'
implementation 'com.google.firebase:firebase-dynamic-links-ktx'
}
Firebase Analytics
Firebase Analytics provides insights into app usage and user engagement.
Basic Event Logging
val firebaseAnalytics = Firebase.analytics
// Log a simple event
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT) {
param(FirebaseAnalytics.Param.ITEM_ID, "id123")
param(FirebaseAnalytics.Param.ITEM_NAME, "Product Name")
param(FirebaseAnalytics.Param.CONTENT_TYPE, "product")
}
Custom Events
fun logViewItem(tag: String, category: String, packageName: String) {
val bundle = Bundle().apply {
putString("Tag", tag)
putString("Category", category)
putString("PackageName", packageName)
}
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle)
}
Predefined Events
Firebase provides predefined events for common scenarios:
FirebaseAnalytics.Event.ADD_TO_CARTFirebaseAnalytics.Event.PURCHASEFirebaseAnalytics.Event.SIGN_UPFirebaseAnalytics.Event.LOGINFirebaseAnalytics.Event.VIEW_ITEM
Debugging Analytics
Enable Verbose Logging
adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC
Debug View (Real-time)
Send events directly to the Debug View in Firebase Console:
# Enable debug mode
adb shell setprop debug.firebase.analytics.app your.package.name
# Disable debug mode
adb shell setprop debug.firebase.analytics.app .none.
Best Practices for Analytics
- Use Categories: To distinguish data within events, use category parameters
- Consistent Naming: Follow a consistent naming convention for custom events
- Don’t Over-log: Focus on meaningful events that provide actionable insights
Firebase Cloud Messaging (FCM)
FCM enables push notifications and messaging to your Android app.
Setup
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
// Send token to your server
sendTokenToServer(token)
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Handle notification
remoteMessage.notification?.let { notification ->
showNotification(notification.title, notification.body)
}
// Handle data payload
if (remoteMessage.data.isNotEmpty()) {
handleDataPayload(remoteMessage.data)
}
}
private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
val pendingIntent = PendingIntent.getActivity(
this, 0, intent,
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
val channelId = "default_channel"
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build()
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.notify(0, notification)
}
}
Manifest Configuration
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Get FCM Token
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
val token = task.result
Log.d("FCM", "Token: $token")
}
}
Topic Subscription
// Subscribe to topic
FirebaseMessaging.getInstance().subscribeToTopic("news")
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("FCM", "Subscribed to news topic")
}
}
// Unsubscribe from topic
FirebaseMessaging.getInstance().unsubscribeFromTopic("news")
Push Delivery Challenges
Push notification delivery rates can vary significantly, especially in regions with network issues:
Factors Affecting Delivery
- Network connectivity
- Battery optimization settings
- Device manufacturer restrictions (e.g., Xiaomi, Huawei)
- App background restrictions
Firebase Dynamic Links
Dynamic Links are smart URLs that direct users to specific content based on context (app installed, platform, etc.).
Features
- Short Links: Google-provided shortened URLs
- Smart Routing: Different behavior based on app installation status
- App installed: Open specific screen (deep link)
- App not installed: Redirect to Play Store or custom URL
- Desktop: Redirect to web URL
Creating Dynamic Links
Firebase Console
- Go to Firebase Console > Dynamic Links
- Create a new dynamic link with:
- Long link URL
- iOS behavior
- Android behavior
- Campaign tracking options
Programmatically
val dynamicLink = Firebase.dynamicLinks.dynamicLink {
link = Uri.parse("https://example.com/product?id=123")
domainUriPrefix = "https://example.page.link"
androidParameters("com.example.android") {
minimumVersion = 125
}
socialMetaTagParameters {
title = "Check out this product"
description = "Amazing product description"
imageUrl = Uri.parse("https://example.com/image.png")
}
}
val dynamicLinkUri = dynamicLink.uri
Create Short Link
val shortLinkTask = Firebase.dynamicLinks.shortLinkAsync {
longLink = Uri.parse(dynamicLink.uri.toString())
}.addOnSuccessListener { (shortLink, flowchartLink) ->
// Short link created
Log.d("DynamicLinks", "Short link: $shortLink")
}
Handling Dynamic Links
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handleDynamicLink()
}
private fun handleDynamicLink() {
Firebase.dynamicLinks
.getDynamicLink(intent)
.addOnSuccessListener { pendingDynamicLinkData ->
val deepLink: Uri? = pendingDynamicLinkData?.link
deepLink?.let { link ->
// Handle the deep link
val productId = link.getQueryParameter("id")
navigateToProduct(productId)
}
}
.addOnFailureListener { e ->
Log.e("DynamicLinks", "Error getting dynamic link", e)
}
}
}
Deep Link Behavior
| Scenario | Behavior |
|---|---|
| App installed | Open app to specific screen |
| App not installed (mobile) | Redirect to Play Store |
| Desktop | Redirect to configured web URL |
| Instant App enabled | Launch Instant App |
Campaign Tracking
Add UTM parameters for campaign tracking:
val dynamicLink = Firebase.dynamicLinks.dynamicLink {
link = Uri.parse("https://example.com/promo")
domainUriPrefix = "https://example.page.link"
googleAnalyticsParameters {
source = "email"
medium = "newsletter"
campaign = "summer_sale"
}
}
Best Practices
Analytics
- Use meaningful event names and parameters
- Enable debug mode during development
- Test events appear in Debug View before release
FCM
- Handle both notification and data payloads
- Create notification channels for Android 8.0+
- Test on various device manufacturers (especially Chinese OEMs)
Dynamic Links
- Always provide fallback URLs
- Use social meta tags for link previews
- Track campaign performance with UTM parameters
Troubleshooting
Analytics Events Not Appearing
- Check if debug mode is enabled
- Verify internet connectivity
- Wait up to 24 hours for events to appear in dashboard
FCM Token Issues
- Ensure Google Play Services is available
- Check if app is properly configured in Firebase Console
- Verify
google-services.jsonis up to date
Dynamic Links Not Working
- Verify domain prefix is properly configured
- Check if app SHA fingerprints are registered
- Test with Firebase Dynamic Links Test Tool
Comments