Kotlin Copilot: Jetpack compose get device ID
Video: Kotlin Copilot: Jetpack compose get device ID by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin Copilot: Jetpack Compose Get Device ID
In this example, you'll learn how to retrieve the unique device ID within a Jetpack Compose app using Kotlin. Accessing the device ID can be useful for analytics, user identification, or device-specific features, while respecting Android's permission model.
Code
import android.content.Context
import android.provider.Settings
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
@Composable
fun DeviceIdDisplay() {
val context = LocalContext.current
// Remember the device ID to avoid recomputing on recomposition
val deviceId = remember {
getDeviceId(context)
}
Text(text = "Device ID: $deviceId")
}
// Function to get the ANDROID_ID, a unique device identifier
fun getDeviceId(context: Context): String {
return Settings.Secure.getString(
context.contentResolver,
Settings.Secure.ANDROID_ID
) ?: "Unknown"
}
Key Points
- Use
Settings.Secure.ANDROID_IDto retrieve a unique device identifier without special permissions. - Access the
Contextinside a composable viaLocalContext.current. - Use
rememberto cache the device ID and prevent unnecessary recomputations during recomposition. - The ANDROID_ID is stable for the device but can reset after a factory reset or on some devices.
- Always consider user privacy and avoid using device IDs for tracking without consent.