diff --git a/android/src/main/java/com/amplitude/android/plugins/AndroidContextPlugin.kt b/android/src/main/java/com/amplitude/android/plugins/AndroidContextPlugin.kt index 1bc4777c..810316fc 100644 --- a/android/src/main/java/com/amplitude/android/plugins/AndroidContextPlugin.kt +++ b/android/src/main/java/com/amplitude/android/plugins/AndroidContextPlugin.kt @@ -38,19 +38,19 @@ class AndroidContextPlugin : Plugin { if (!configuration.newDeviceIdPerInstall && configuration.useAdvertisingIdForDeviceId && !contextProvider.isLimitAdTrackingEnabled()) { val advertisingId = contextProvider.advertisingId if (advertisingId != null && validDeviceId(advertisingId)) { - amplitude.setDeviceId(advertisingId) + setDeviceId(advertisingId) return } } if (configuration.useAppSetIdForDeviceId) { val appSetId = contextProvider.appSetId if (appSetId != null && validDeviceId(appSetId)) { - amplitude.setDeviceId("${appSetId}S") + setDeviceId("${appSetId}S") return } } val randomId = AndroidContextProvider.generateUUID() + "R" - amplitude.setDeviceId(randomId) + setDeviceId(randomId) } private fun applyContextData(event: BaseEvent) { @@ -144,6 +144,10 @@ class AndroidContextPlugin : Plugin { } } + private fun setDeviceId(deviceId: String) { + amplitude.idContainer.identityManager.editIdentity().setDeviceId(deviceId).commit() + } + companion object { const val PLATFORM = "Android" const val SDK_LIBRARY = "amplitude-analytics-android" diff --git a/android/src/test/java/com/amplitude/android/AmplitudeTest.kt b/android/src/test/java/com/amplitude/android/AmplitudeTest.kt index 3faf6fcb..e2e1bb06 100644 --- a/android/src/test/java/com/amplitude/android/AmplitudeTest.kt +++ b/android/src/test/java/com/amplitude/android/AmplitudeTest.kt @@ -182,6 +182,47 @@ class AmplitudeTest { } } + @Test + fun test_setDeviceId_generatedDeviceIdShouldBeUsed() = runTest { + setDispatcher(testScheduler) + val n = 100 + val clients = arrayOfNulls(n) + for (i in 0 until n) { + val configuration = createConfiguration() + configuration.instanceName = "generated-instance-$i" + val amplitude = Amplitude(configuration) + clients[i] = amplitude + } + + advanceUntilIdle() + Thread.sleep(1000) + + for (i in 0 until n) { + Assertions.assertTrue(clients[i]?.getDeviceId()?.endsWith('R') ?: false) + } + } + + @Test + fun test_setDeviceId_customDeviceIdShouldBeUsed() = runTest { + setDispatcher(testScheduler) + val n = 100 + val clients = mutableListOf() + for (i in 0 until n) { + val configuration = createConfiguration() + configuration.instanceName = "custom-instance-$i" + val amplitude = Amplitude(configuration) + amplitude.setDeviceId("custom-device-$i") + clients.add(amplitude) + } + + advanceUntilIdle() + Thread.sleep(1000) + + for (i in 0 until n) { + Assertions.assertEquals("custom-device-$i", clients[i].getDeviceId()) + } + } + companion object { const val instanceName = "testInstance" }