Chapter 163 · Omnibus Instrument Product Analytics
Subchapter 163.5
references/EXAMPLE-android.mdMarkdown50 KBView on GitHub
Repository: https://github.com/PostHog/context-mill Path: basics/android
This is an Android example demonstrating PostHog integration with product analytics, session replay, and error tracking using Kotlin and Jetpack Compose.
This example uses the PostHog Android SDK (posthog-android) to provide automatic PostHog integration with built-in error tracking, session replay, and simplified configuration.
The PostHog configuration is stored in local.properties (this file is gitignored):
# PostHog configuration
posthog.apiKey=your_posthog_project_token
posthog.host=https://us.i.posthog.comAlternatively, you can configure PostHog in your build.gradle file:
android {
defaultConfig {
buildConfigField "String", "POSTHOG_PROJECT_TOKEN", "\"your_posthog_project_token\""
buildConfigField "String", "POSTHOG_HOST", "\"https://us.i.posthog.com\""
}
}Get your PostHog project token from your PostHog project settings (opens in a new tab).
├── app/
│ ├── src/
│ │ ├── main/
│ │ │ ├── java/com/example/posthog/
│ │ │ │ ├── BurritoApplication.kt # Application class with PostHog initialization
│ │ │ │ ├── MainActivity.kt # Main activity
│ │ │ │ ├── ui/
│ │ │ │ │ ├── screens/
│ │ │ │ │ │ ├── LoginScreen.kt # Login screen with user identification
│ │ │ │ │ │ ├── BurritoScreen.kt # Demo feature screen with event tracking
│ │ │ │ │ │ └── ProfileScreen.kt # User profile with error tracking demo
│ │ │ │ │ └── components/ # Reusable UI components
│ │ │ │ └── utils/
│ │ │ │ └── PostHogHelper.kt # PostHog utility functions
│ │ │ ├── res/ # Resources (layouts, strings, etc.)
│ │ │ └── AndroidManifest.xml # App manifest
│ │ └── test/ # Unit tests
│ └── build.gradle # App-level Gradle configuration
├── build.gradle # Project-level Gradle configuration
├── settings.gradle # Gradle settings
└── local.properties # Local configuration (gitignored)PostHog is initialized in the Application class to ensure it’s available throughout the app lifecycle:
class BurritoApplication : Application() {
override fun onCreate() {
super.onCreate()
val posthogConfig = PostHogConfig(
apiKey = BuildConfig.POSTHOG_PROJECT_TOKEN,
host = BuildConfig.POSTHOG_HOST
).apply {
// Enable session replay
sessionReplay = true
// Enable automatic exception capture
captureApplicationLifecycleEvents = true
captureDeepLinks = true
captureScreenViews = true
}
PostHog.setup(this, posthogConfig)
}
}Key Points:
onCreate() to ensure it’s initialized as early as possibleBuildConfig (set in build.gradle)AndroidManifest.xmlUsers are identified when they log in:
val posthog = PostHog.getInstance()
fun handleLogin(username: String, password: String) {
// Authenticate user
val success = authenticateUser(username, password)
if (success) {
// Identify the user once on login/sign up
posthog.identify(
distinctId = username,
properties = mapOf(
"username" to username,
"login_method" to "password"
)
)
// Capture login event
posthog.capture("user_logged_in", mapOf(
"username" to username
))
}
}Key Points:
identify() is called once when the user logs in or signs upcapture() with event names and propertiesdistinctId should be a unique identifier for the userCustom events are tracked throughout the app:
val posthog = PostHog.getInstance()
fun handleBurritoConsideration() {
// Track custom event
posthog.capture("burrito_considered", mapOf(
"total_considerations" to considerationCount,
"username" to currentUser.username,
"timestamp" to System.currentTimeMillis()
))
// Update user properties
posthog.setUserProperties(mapOf(
"last_burrito_consideration" to System.currentTimeMillis(),
"total_burrito_considerations" to considerationCount
))
}Key Points:
capture() methodsetUserProperties()Errors are captured automatically and can also be tracked manually:
Automatic Error Capture: PostHog automatically captures uncaught exceptions when configured:
val posthogConfig = PostHogConfig(
apiKey = BuildConfig.POSTHOG_PROJECT_TOKEN,
host = BuildConfig.POSTHOG_HOST
).apply {
// Automatic exception capture is enabled by default
captureApplicationLifecycleEvents = true
}Manual Error Capture:
val posthog = PostHog.getInstance()
try {
// Risky operation
performRiskyOperation()
} catch (e: Exception) {
// Capture exception manually
posthog.captureException(e, mapOf(
"context" to "burrito_consideration",
"user_id" to currentUser.id
))
}Screen views are automatically tracked when captureScreenViews is enabled. You can also manually track screen views:
val posthog = PostHog.getInstance()
// Manual screen view tracking
posthog.screen("BurritoScreen", mapOf(
"screen_category" to "features",
"user_type" to "premium"
))Session replay is enabled in the PostHog configuration:
val posthogConfig = PostHogConfig(
apiKey = BuildConfig.POSTHOG_PROJECT_TOKEN,
host = BuildConfig.POSTHOG_HOST
).apply {
sessionReplay = true
sessionReplayConfig = SessionReplayConfig(
maskAllInputs = false, // Set to true to mask all input fields
maskAllText = false // Set to true to mask all text
)
}PostHog is accessed via the singleton instance:
val posthog = PostHog.getInstance()
posthog.capture("event_name", mapOf("property" to "value"))The instance is available throughout your application after initialization.
android {
defaultConfig {
// PostHog configuration
buildConfigField "String", "POSTHOG_PROJECT_TOKEN", "\"${project.findProperty("posthog.apiKey") ?: ""}\""
buildConfigField "String", "POSTHOG_HOST", "\"${project.findProperty("posthog.host") ?: "https://us.i.posthog.com"}\""
}
}
dependencies {
// PostHog Android SDK
implementation 'com.posthog:posthog-android:3.+'
// Other dependencies...
}The local.properties file is automatically read by Gradle:
def localProperties = new Properties()
localProperties.load(new FileInputStream(rootProject.file("local.properties")))
android {
defaultConfig {
buildConfigField "String", "POSTHOG_PROJECT_TOKEN", "\"${localProperties.getProperty("posthog.apiKey", "")}\""
buildConfigField "String", "POSTHOG_HOST", "\"${localProperties.getProperty("posthog.host", "https://us.i.posthog.com")}\""
}
}Application.onCreate() methodidentify() once when the user logs in or signs upuser_logged_in instead of login)package com.example.posthog
import android.app.Application
import com.posthog.android.PostHogAndroid
import com.posthog.android.PostHogAndroidConfig
class BurritoApplication : Application() {
override fun onCreate() {
super.onCreate()
// Initialize PostHog early in Application lifecycle
val config = PostHogAndroidConfig(
apiKey = BuildConfig.POSTHOG_PROJECT_TOKEN,
host = BuildConfig.POSTHOG_HOST,
).apply {
debug = true
errorTrackingConfig.autoCapture = true
}
PostHogAndroid.setup(this, config)
}
}
package com.example.posthog.data
data class User(
val username: String,
val burritoConsiderations: Int = 0
)
package com.example.posthog.data
import android.content.Context
import android.content.SharedPreferences
import org.json.JSONObject
class UserRepository(context: Context) {
private val prefs: SharedPreferences = context.getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE
)
companion object {
private const val PREFS_NAME = "burrito_app_prefs"
private const val KEY_CURRENT_USERNAME = "current_username"
private const val KEY_USER_DATA_PREFIX = "user_data_"
}
fun getCurrentUsername(): String? {
return prefs.getString(KEY_CURRENT_USERNAME, null)
}
fun getUser(username: String): User? {
val json = prefs.getString("$KEY_USER_DATA_PREFIX$username", null) ?: return null
return try {
val obj = JSONObject(json)
User(
username = obj.getString("username"),
burritoConsiderations = obj.getInt("burritoConsiderations")
)
} catch (e: Exception) {
null
}
}
fun saveUser(user: User) {
val json = JSONObject().apply {
put("username", user.username)
put("burritoConsiderations", user.burritoConsiderations)
}.toString()
prefs.edit()
.putString("$KEY_USER_DATA_PREFIX${user.username}", json)
.putString(KEY_CURRENT_USERNAME, user.username)
.apply()
}
fun clearCurrentUser() {
prefs.edit()
.remove(KEY_CURRENT_USERNAME)
.apply()
}
fun getCurrentUser(): User? {
val username = getCurrentUsername() ?: return null
return getUser(username)
}
}
package com.example.posthog
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
package com.example.posthog.navigation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.posthog.ui.screens.BurritoScreen
import com.example.posthog.ui.screens.HomeScreen
import com.example.posthog.ui.screens.ProfileScreen
import com.example.posthog.viewmodel.AuthViewModel
sealed class Screen(val route: String) {
object Home : Screen("home")
object Burrito : Screen("burrito")
object Profile : Screen("profile")
}
@Composable
fun NavGraph(
navController: NavHostController,
viewModel: AuthViewModel
) {
val isAuthenticated by viewModel.isAuthenticated.collectAsState()
val currentUser by viewModel.currentUser.collectAsState()
NavHost(
navController = navController,
startDestination = Screen.Home.route
) {
composable(Screen.Home.route) {
HomeScreen(
isAuthenticated = isAuthenticated,
username = currentUser?.username,
onLogin = { username -> viewModel.login(username) }
)
}
composable(Screen.Burrito.route) {
if (!isAuthenticated) {
LaunchedEffect(Unit) {
navController.navigate(Screen.Home.route) {
popUpTo(Screen.Home.route) { inclusive = true }
}
}
} else {
BurritoScreen(
burritoCount = currentUser?.burritoConsiderations ?: 0,
onConsiderBurrito = { viewModel.incrementBurritoCount() }
)
}
}
composable(Screen.Profile.route) {
if (!isAuthenticated) {
LaunchedEffect(Unit) {
navController.navigate(Screen.Home.route) {
popUpTo(Screen.Home.route) { inclusive = true }
}
}
} else {
ProfileScreen(
username = currentUser?.username ?: "",
burritoCount = currentUser?.burritoConsiderations ?: 0
)
}
}
}
}
package com.example.posthog.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.posthog.ui.theme.DarkHeader
import com.example.posthog.ui.theme.ErrorRed
import com.example.posthog.ui.theme.White
@Composable
fun AppHeader(
isAuthenticated: Boolean,
username: String?,
currentRoute: String?,
onNavigate: (String) -> Unit,
onLogout: () -> Unit
) {
Box(
modifier = Modifier
.fillMaxWidth()
.background(DarkHeader)
.padding(horizontal = 16.dp, vertical = 12.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
// App title
Text(
text = "Burrito App",
color = White,
fontSize = 18.sp
)
// User section (right side)
if (isAuthenticated && username != null) {
Row(
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = username,
color = White,
fontSize = 14.sp
)
Button(
onClick = onLogout,
colors = ButtonDefaults.buttonColors(
containerColor = ErrorRed
),
shape = RoundedCornerShape(4.dp),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 6.dp)
) {
Text(
text = "Logout",
color = White,
fontSize = 14.sp
)
}
}
}
}
}
}
package com.example.posthog.ui.components
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import
package com.example.posthog.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.posthog.ui.theme.LightGray
import com.example.posthog.ui.theme.TextDark
import com.example.posthog.ui.theme.TextGray
@Composable
fun StatsCard(
title: String,
value: String,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxWidth()
.background(
color = LightGray,
shape = RoundedCornerShape(4.dp)
)
.padding(16.dp)
) {
Text(
text = title,
color = TextGray,
fontSize = 14.sp
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = value,
color = TextDark,
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
}
}
package com.example.posthog.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
package com.example.posthog.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
package com.example.posthog.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
package com.example.posthog.ui.theme
import androidx.compose.ui.graphics.Color
val PrimaryBlue = Color(0xFF0070F3)
val PrimaryBlueHover = Color(0xFF0051CC)
val SuccessGreen = Color(0xFF28A745)
val SuccessGreenHover = Color(0xFF218838)
val ErrorRed = Color(0xFFDC3545)
val ErrorRedHover = Color(0xFFC82333)
val DarkHeader = Color(0xFF333333)
val DarkHeaderHover = Color(0xFF555555)
val LightGray = Color(0xFFF8F9FA)
val BorderGray = Color(0xFFDDDDDD)
val TextGray = Color(0xFF666666)
val BackgroundGray = Color(0xFFF5F5F5)
val TextDark = Color(0xFF333333)
val White = Color(0xFFFFFFFF)
package com.example.posthog.ui.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
private val LightColorScheme = lightColorScheme(
primary = PrimaryBlue,
secondary = SuccessGreen,
tertiary = DarkHeader,
background = BackgroundGray,
surface = White,
onPrimary = White,
onSecondary = White,
onTertiary = White,
onBackground = TextDark,
onSurface = TextDark
)
@Composable
fun PostHogTheme(
content: @Composable () -> Unit
) {
MaterialTheme(
colorScheme = LightColorScheme,
typography = Typography,
content = content
)
}package com.example.posthog.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Typography based on design specification
// Uses system font stack (FontFamily.Default maps to Roboto on Android)
val Typography = Typography(
// H1 - Page titles (32sp)
displayLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 32.sp,
lineHeight = 40.sp,
letterSpacing = 0.sp
),
// H2 - Section titles (24sp)
displayMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 24.sp,
lineHeight = 32.sp,
letterSpacing = 0.sp
),
// H3 - Subsection titles (20sp)
displaySmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.SemiBold,
fontSize = 20.sp,
lineHeight = 26.sp,
letterSpacing = 0.sp
),
// Body text (16sp with 1.6 line height = 25.6sp)
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 26.sp,
letterSpacing = 0.sp
),
// Small/Note text (14sp)
bodySmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 21.sp,
letterSpacing = 0.sp
),
// Labels (16sp, medium weight)
labelLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.sp
),
// Button text - Burrito button (18sp)
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 18.sp,
lineHeight = 24.sp,
letterSpacing = 0.sp
),
// Button text - Primary/Logout (16sp/14sp)
titleMedium = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.sp
),
titleSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.sp
)
)package com.example.posthog.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.posthog.data.User
import com.example.posthog.data.UserRepository
import com.posthog.PostHog
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class AuthViewModel(application: Application) : AndroidViewModel(application) {
private val repository = UserRepository(application)
private val _currentUser = MutableStateFlow<User?>(null)
val currentUser: StateFlow<User?> = _currentUser.asStateFlow()
private val _isAuthenticated = MutableStateFlow(false)
val isAuthenticated: StateFlow<Boolean> = _isAuthenticated.asStateFlow()
init {
loadCurrentUser()
}
private fun loadCurrentUser() {
viewModelScope.launch {
val user = repository.getCurrentUser()
_currentUser.value = user
_isAuthenticated.value = user != null
}
}
fun login(username: String) {
viewModelScope.launch {
val existingUser = repository.getUser(username)
val user = existingUser ?: User(username = username, burritoConsiderations = 0)
repository.saveUser(user)
_currentUser.value = user
_isAuthenticated.value = true
PostHog.identify(username)
PostHog.capture(event = "user_logged_in")
}
}
fun logout() {
viewModelScope.launch {
PostHog.capture("user_logged_out")
PostHog.reset()
repository.clearCurrentUser()
_currentUser.value = null
_isAuthenticated.value = false
}
}
fun incrementBurritoCount() {
viewModelScope.launch {
val user = _currentUser.value ?: return@launch
val updatedUser = user.copy(burritoConsiderations = user.burritoConsiderations + 1)
repository.saveUser(updatedUser)
_currentUser.value = updatedUser
PostHog.capture(
event = "burrito_considered",
properties = mapOf(
"total_considerations" to updatedUser.burritoConsiderations,
"username" to updatedUser.username
)
)
}
}
}
This file