Guía del desarrollador
Follow this section to install and configure the Android SDK in your Android app and learn about advanced features.Primeros pasos
Follow these steps to install and configure the Kameleoon Android SDK in your application.Instalación
Puede instalar el SDK de Android añadiendo la siguiente dependencia al archivobuild.gradle de su aplicación Android:
Configuración adicional
To customize the SDK’s behavior, create a.properties configuration file. The properties file’s name and location are important:
- Create the file in you app’s
assets/directory. - Name the file
kameleoon-client.properties.
If you specify a
visitorCode and set the isUniqueIdentifier parameter to true, the SDK methods use the visitorCode value as the unique visitor identifier, which is useful for cross-device experimentation. The SDK links the flushed data to the visitor that is associated with the specified identifier.isUniqueIdentifier puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitorCode anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.Using activityTrackingIntervalMillisecond
El parámetro activityTrackingIntervalMillisecond ayuda a reducir el uso de red y el consumo de batería al controlar con qué frecuencia el SDK envía un evento de actividad para prolongar la sesión del visitante en la Data API. El valor por defecto y el valor mínimo permitido es 60 000 ms (60 segundos); cualquier valor menor distinto de cero se ignora y se aplica el valor por defecto. Los temporizadores se pausan cuando la aplicación está en segundo plano, por lo que el intervalo solo avanza efectivamente mientras la aplicación está en primer plano.
Review its impact on the following features:
-
Elapsed time triggers
- If the configured elapsed time is shorter than the tracking interval, the trigger will not fire as expected.
-
Elapsed time segments
- If the elapsed time is shorter than the tracking interval, users may not be included in the segment as intended.
-
Time spent goals
- If the elapsed time is shorter than the tracking interval, the goal may never be reached.
-
Time elapsed since last visit in the results page
- Measurements for “time elapsed since last visit” become less precise when the elapsed time is close to or below the tracking interval.
-
Visits count
- A new visit is created after 30 minutes of inactivity. If the tracking interval is longer than 30 thirty minutes, a new visit will be created at each tracking interval.
Initialize the Kameleoon Client
After installing the SDK in your application and setting up the app properties, you must create the Kameleoon Client. A Client is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all of the methods and properties you need to run a feature flag.- Java
- Kotlin
KameleoonClientFactory.create() method initializes the client, but it is not immediately ready for use. This delay is because the Kameleoon Client must retrieve the current configuration of feature flags (along with their traffic repartition) from a Kameleoon remote server. This retrieval requires network access, which is not always available. Until the Kameleoon Client is fully ready, you should not attempt to run other methods in the Kameleoon Android SDK. Note that once the first configuration of the feature flags is fetched, it is then periodically refreshed, but even if the refresh fails for any reason, the Kameleoon client will continue to function using the previous configuration.
Puede usar el método isReady() para comprobar si la inicialización del cliente Kameleoon ha finalizado.
Alternatively, a helper callback can encapsulate the logic of feature flag triggering and variation implementation. The best approach (isReady() or callback) depends on preferences and the exact use case. Using isReady() is recommended when the SDK is expected to be ready for use soon. Por ejemplo, isReady() is appropriate when running a feature flag on a dialog that users likely won’t access for the first few seconds or minutes of navigating in the app. A callback is recommended when there is a high probability that the SDK is still initializing. Por ejemplo, a feature flag that appears onscreen at the application launch should use a callback that makes the application wait until the SDK is ready or a specified timeout has expired.
It’s your responsibility as the app developer to ensure the logic of your application code is correct within the context of A/B testing using Kameleoon. A good practice is to always assume that the application user can be left out of the feature flag when the Kameleoon client is not yet ready. This exclusion is easy to implement, because this corresponds to the implementation of the default or reference variation logic. The code samples in the next paragraph show examples of this approach.
Best practices for initialization and usage
- Initializing
KameleoonClientas a singleton as early as possible after the application starts is recommended, as initialization may take some time. Since initialization is asynchronous, it does not block or delay the application startup process. - Before using
KameleoonClient, verify that it is initialized by calling therunWhenReadymethod. Otherwise, attempts to use the client before it is ready will result in errors. - ⚠️ Most key methods may throw exceptions, so proper exception handling is required. Be sure to review the documentation for each method you use to understand its potential exceptions.
- Java
- Kotlin
- Kotlin (Coroutines)
Activación de un feature flag
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon. Para determinar el estado o la variación de un feature flag para un usuario específico, debe utilizar el métodogetVariation() o isFeatureActive() para recuperar la configuración basada en el featureKey.
El método getVariation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del featureKey y el visitorCode.
El método isFeatureActive() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.
Si su feature flag tiene variables asociadas (como comportamientos específicos vinculados a cada variación), getVariation() también le permite acceder al objeto Variation, que proporciona detalles sobre la variación asignada y su experimento asociado. Este método comprueba si el usuario está segmentado, encuentra la variación asignada al visitante y la guarda en almacenamiento. Cuando track=true, el SDK enviará el evento de exposición al experimento especificado en la siguiente solicitud de seguimiento, que se desencadena automáticamente según el tracking_interval_millisecond del SDK. De forma predeterminada, este intervalo está configurado en 1000 milisegundos (1 segundo).
El método getVariation() le permite controlar si se realiza el seguimiento. Si track=false, el SDK no enviará eventos de exposición. Esto es útil si prefiere no realizar el seguimiento de los datos a través del SDK y, en su lugar, basarse en el seguimiento del lado del cliente gestionado por el motor de Kameleoon, por ejemplo. Además, establecer track=false resulta útil cuando se utiliza el método getVariations(), donde puede que solo necesite las variaciones de todos los flags sin desencadenar eventos de seguimiento. Si desea saber más sobre cómo funciona el seguimiento, consulte este artículo
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
Para segmentar a un usuario, asegúrese de haber añadido los puntos de datos relevantes a su perfil antes de recuperar la variación de la funcionalidad o comprobar si el flag está activo. Utilice el métodoaddData() para añadir estos puntos de datos al perfil del usuario.
To retrieve data points collected on other devices, use the getRemoteVisitorData() method. This method asynchronously fetches data from the servers. It is important to call getRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.
Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema.
Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device. See the complete list here.
Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Seguimiento de conversiones de objetivos
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el métodotrackConversion() y proporcione el parámetro requerido goalId.
La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval_millisecond). Si prefiere enviar la solicitud de inmediato, utilice el método flush() con el parámetro instant=true.
Experimentación entre dispositivos
Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.Sincronización de datos personalizados entre dispositivos
Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado: Mismo ID de usuario en todos los dispositivos Si el mismo ID de usuario se utiliza de forma consistente en todos los dispositivos, la sincronización se gestiona automáticamente sin necesidad de una sincronización de mapeo personalizado. Basta con llamar al métodogetRemoteVisitorData() cuando desee sincronizar los datos recopilados entre varios dispositivos.
Instancias multi-servidor con IDs consistentes
En configuraciones complejas que involucran varios servidores (por ejemplo, instancias de servidor distribuidas), donde el mismo ID de usuario está disponible en todos los servidores, la sincronización entre servidores (con getRemoteVisitorData()) es suficiente sin necesidad de una sincronización adicional de mapeo personalizado.
Los clientes que necesiten datos adicionales pueden consultar la descripción del método getRemoteVisitorData() para obtener más orientación. En el código siguiente se asume que el mismo identificador único (en este caso, el visitorCode, que también puede denominarse userId) se utiliza de manera consistente entre los dos dispositivos para una recuperación precisa de los datos.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
- Java
- Kotlin
- Kotlin (Coroutines)
Device A
Device B
Uso de datos personalizados para la fusión de sesiones
La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utiliceCustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada.
Una vez habilitada la reconciliación entre dispositivos, al llamar a getRemoteVisitorData() con el parámetro userId se recuperan todos los datos conocidos para un usuario determinado.
Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.
La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí.
Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon.
Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
getRemoteVisitorData()with passedisUniqueIdentifier=truetoKameleoonClientConfig- to retrieve data for all linked visitors.trackConversion()orflush()with passedisUniqueIdentifier=truetoKameleoonClientConfig- to track some data for specific visitor that is associated with another visitor.
- Java
- Kotlin
- Kotlin (Coroutines)
getVisitorCode(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.
Uso de una clave de bucketing personalizada
De forma predeterminada, Kameleoon utiliza un ID de visitante anónimo y único (visitorCode) para asignar usuarios a las variaciones de los feature flags. Este ID se genera y almacena habitualmente en el dispositivo del usuario (en una cookie del navegador para los SDKs del lado del cliente y del lado del servidor, y en almacenamiento persistente para los SDKs móviles). Sin embargo, en determinados escenarios puede necesitar asegurarse de que todos los usuarios de la misma organización vean la misma variante de un feature flag.
La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitorCode predeterminado.
Casos de uso
El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:- Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como
accountId. Las claves de bucketing personalizadas son cruciales para probar mediante A/B funcionalidades que afecten a todo un equipo o empresa.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:- Java
- Kotlin
- Proporcionar la clave personalizada: Usted proporciona su identificador personalizado al SDK de Kameleoon mediante el método
addData(). En este método, pasará la clave de bucketing personalizada que haya elegido como un objetoCustomData. Aquí,newVisitorCodehace referencia al identificador que desea usar para el bucketing (por ejemplo, el nuevouserIdoaccountId).
- Lógica de bucketing: Una vez que se proporciona una clave de bucketing personalizada a través del método
addData(), todos los cálculos de hash para asignar usuarios a las variaciones utilizarán estenewVisitorCode(su clave personalizada) en lugar delvisitorCodepredeterminado. Usar elnewVisitorCodesignifica que la decisión de bucketing queda ligada a su identificador personalizado, garantizando asignaciones consistentes en los diversos contextos en los que esté presente ese identificador. - Seguimiento de datos y analítica: Es crucial tener en cuenta que, aunque el
newVisitorCode(su clave personalizada) se utiliza para las decisiones de bucketing, todos los datos posteriores (eventos de seguimiento y conversiones, por ejemplo) se envían y se asocian con elvisitorCodeoriginal. Esta separación garantiza que su analítica refleje con precisión los recorridos e interacciones individuales de los usuarios dentro del contexto más amplio de su experimento, incluso cuando el bucketing se realiza a un nivel superior (como una cuenta) o a través de varios dispositivos/sesiones. Sus datos originales del visitante permanecen intactos para una elaboración de informes completa.
Requisitos técnicos
Para utilizar eficazmente una clave de bucketing personalizada:- La clave debe ser un
String. - Debe ser única para la entidad que pretende agrupar (por ejemplo, si utiliza un
userId, el ID de cada usuario debe ser único). - La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios. También puede utilizar sus propios datos externos para segmentar a los usuarios.Error Handling
All methods of the Kameleoon SDK can throw onlyKameleoonException or its documented inherited exceptions (listed in the Exceptions Thrown section for each method).
These exceptions are expected behavior of the SDK. If you want to handle specific scenarios differently, you can catch individual inherited exceptions; otherwise, catching KameleoonException will handle all SDK‑related errors.
Although our unit and integration tests confirm that the SDK never throws Exception or RuntimeException, we understand that patching SDK versions on Android can be difficult, and unexpected issues may arise from third‑party libraries that could throw a RuntimeException. To prevent your application from crashing in such rare cases, we recommend that you also catch Exception (or RuntimeException) as an additional safeguard. This is strictly a precaution and not an expected behavior of the SDK.
Por ejemplo:
- Java
- Kotlin
Registro de eventos
El SDK genera registros que reflejan diversos procesos internos y problemas.Niveles de registro
El SDK admite la configuración para limitar el registro mediante un nivel de log.- Java
- Kotlin
Gestión personalizada de los registros
El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
- Java
- Kotlin
Passing the visitor code to a WebView
In some cases, you may need to pass the visitor code from the native application to a WebView that uses Engine.js or the web JavaScript or React SDKs. The following example demonstrates the recommended way to achieve this:- Kotlin
- Kotlin (Jetpack Compose)
- Java
Referencia
This is the full reference documentation for the Kameleoon Android SDK.Inicialización
Once you have installed the SDK in your application, the first step is initializing Kameleoon. All of your application’s interactions with the SDK, such as triggering an experiment, are accomplished using this Kameleoon client object.create()
Llame a este método antes que a cualquier otro para inicializar el SDK. Este método se encuentra encom.kameleoon.KameleoonClientFactory. Su aplicación realiza todas las interacciones con el SDK utilizando el objeto KameleoonClient resultante que este método crea.
Puede personalizar el comportamiento del SDK (por ejemplo, el entorno, las credenciales, etc.) proporcionando un objeto de configuración. De lo contrario, el SDK intentará encontrar y usar su archivo de configuración.
- Java
- Kotlin
Argumentos
Valor de retorno
Excepciones lanzadas
isReady()
For mobile SDKs, the Kameleoon Client can’t initialize immediately, as it must perform a server call to retrieve the current configuration for the active feature flags. Use este método para check if the SDK is ready by callingisReady() before triggering any feature flags.
Alternatively, you can use a callback (see the runWhenReady() method for details).
- Java
- Kotlin
Valor de retorno
runWhenReady()
- 🔄 Performs an asynchronous request (if the configuration is outdated or missing)
KameleoonClient cannot initialize immediately, as it must perform a server call to retrieve the current configuration for all feature flags. Use the runWhenReady() method to handle the time until the client is ready for use. Additionally, you can set a maximum timeout period to control how long the client will wait before it becomes ready.
If result.getOrThrow()=true, the KameleoonClient is initialized and ready, and the feature flags will be triggered with their respective variations. If the result is false or a timeout occurs, the initialization will not complete successfully.
El callback o el código basado en corutinas debe incluir lógica para aplicar la variación de referencia, ya que el usuario será excluido del feature flag si se produce un timeout.
- Java
- Kotlin
- Kotlin (Coroutines)
Argumentos
Feature flags y variaciones
isFeatureActive()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
This method was previously called
activateFeature, which was removed in SDK version 4.0.0.featureKey como argumento obligatorio para comprobar si la funcionalidad especificada estará activa para un visitante.
If the visitor has never been associated with this feature flag, the method returns a random boolean value (true if the visitor should be shown this feature, otherwise false). If the visitor is already registered with this feature flag, this method returns the previous featureFlag value.
Ensure you properly set up error handling como se muestra en el ejemplo code to catch potential exceptions.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as
isFeatureActive(), getVariation() or getVariations().Use el valor predeterminado true para el parámetro track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro track en false solo si llama a estos métodos antes de exponer a los visitantes.Por ejemplo, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.- Java
- Kotlin
Argumentos
Valor de retorno
Excepciones lanzadas
getVariation()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true.
Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado.
Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
- Java
- Kotlin
Argumentos
Valor de retorno
Excepciones lanzadas
getVariations()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Variation asignados a un visitante dado para todos los feature flags.
Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. It takes onlyActive and track as optional arguments.
- Si
onlyActivese establece entrue, el métodogetVariations()devolverá las variaciones de los feature flags siempre que el usuario no esté asignado a la variaciónoff. - El parámetro
trackcontrola si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set totrue. Si se establece enfalse, el seguimiento estará deshabilitado.
Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag.
Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
- Java
- Kotlin
Argumentos
Valor de retorno
Excepciones lanzadas
setForcedVariation()
El método permite you to programmatically assign a specificVariation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.
Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.
El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.
- Java
- Kotlin
Argumentos
Excepciones lanzadas
En la mayoría de los casos, solo es necesario gestionar el error básico
KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.evaluateAudiences()
- 📨 Envía datos de seguimiento a Kameleoon
evaluateAudiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
- Java
- Kotlin
Excepciones lanzadas
En la mayoría de los casos, solo es necesario gestionar el error básico
KameleoonException, como se muestra en el ejemplo. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.getDataFile()
Devuelve la configuración actual del SDK como un objetoDataFile.
- Java
- Kotlin
Valor de retorno
Errores thrown
Goals
trackConversion()
- 📨 Envía datos de seguimiento a Kameleoon
goalId para hacer seguimiento de la conversión en este objetivo en particular. Además, este método también acepta los argumentos revenue, metadata y negative.
El método trackConversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
- Java
- Kotlin
Argumentos
metadata values are accessible through raw data exports and the results page.Si se proporciona el parámetro
metadata, Kameleoon utilizará estos valores especificados para la conversión actual en lugar de lo recopilado previamente mediante el método addData(). Si se omite el parámetro, Kameleoon utilizará los últimos valores rastreados para esos CustomData antes de la conversión y dentro de la misma visita.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.En el siguiente ejemplo, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).- Java
- Kotlin
Events
onUpdateConfiguration()
This method was previously named
updateConfigurationHandler, which was removed in SDK version 4.0.0 release.onUpdateConfiguration() le permite gestionar el evento cuando la configuración tiene datos actualizados. Toma un parámetro de entrada, completion. El completion que se llamará cuando la configuración se actualice mediante un evento de configuración en tiempo real.
Este handler solo se activa cuando el SDK está en modo streaming (server-sent events). No se llama para actualizaciones de configuración realizadas en el modo polling por defecto (
refreshIntervalMinute).Argumentos
- Java
- Kotlin
Datos del visitante
getVisitorCode()
Returns unique visitor code used in SDK.- Java
- Kotlin
Valor de retorno
addData()
El métodoaddData() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.
El método addData() no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método flush(). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el flush().
El método trackConversion() también envía cualquier dato previamente asociado, al igual que flush(). The same holds true for getVariation() and getVariations() methods if an experimentation rule is triggered.
- Java
- Kotlin
Argumentos
flush()
- 📨 Envía datos de seguimiento a Kameleoon
flush() takes the Kameleoon data associated with a visitor, and sends a tracking request along with all of the data that were added previously using the addData() method that has not yet been sent when calling one of these methods. flush() is non-blocking, as the server call is made asynchronously.
flush() provides control over when the data associated with a visitor is sent to the servers. For instance, if addData() is called a dozen times, sending data to the server after each addData() invocation would be inefficient. Call flush() once at the end.
El método flush() usa visitorCode como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Si establece el parámetro de configuración isUniqueIdentifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
- Java
- Kotlin
Argumentos
getRemoteData()
- 🔄 Performs an asynchronous request
Este método se llamaba anteriormente
retrieveDataFromRemoteSource, que fue eliminado en la versión 4.0.0 del SDK.siteCode and the key argument (or the active visitorCode if the key is omitted). The visitorCode and siteCode are specified in KameleoonClientFactory.create(). Data can be stored quickly and conveniently on highly scalable remote servers using the Kameleoon Data API. The application can then retrieve the data using this method.
- Java
- Kotlin
- Kotlin (Coroutines)
Argumentos
getRemoteVisitorData()
- 🔄 Performs an asynchronous request
getRemoteVisitorData() is an asynchronous method for retrieving Kameleoon Visits Data for the visitor from the Kameleoon Data API. El método añade data to storage for other methods to use when making targeting decisions.
Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:
- utilizar datos recopilados desde otros dispositivos.
- access a user’s history, such as custom data collected during previous visits.
De forma predeterminada,
getRemoteVisitorData() automatically retrieves the latest stored custom data with scope=Visitor and attaches it to the visitor without having to call the method addData(). It is particularly useful for synchronizing custom data between multiple devices.Checking only for failed results is recommended. However, if necessary, it can be verified that the data has been added to the visitor and is available for targeting purposes (or for debugging, though using logging is better for debugging). Additionally, data can be managed manually if the shouldAddData=false parameter is passed.- Java
- Kotlin
- Kotlin (Coroutines)
Argumentos
Using parameters of RemoteVisitorDataFilter
El método getRemoteVisitorData() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Ya sea que esté segmentando en función de objetivos, experimentos o variaciones, el mismo enfoque se aplica a todos los tipos de datos.
Por ejemplo, suppose you want to retrieve data on visitors who completed a goal “Order transaction”. Puede especificar parámetros dentro del método getRemoteVisitorData() para refinar su segmentación. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método getRemoteVisitorData() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available
RemoteVisitorDataFilter options:getVisitorWarehouseAudience()
- 🔄 Performs an asynchronous request
warehouseKey parameter is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details.
- Java
- Kotlin
- Kotlin (Coroutines)
Argumentos
setLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use their personal data. Setting thelegalConsent parameter to false limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.
- Java
- Kotlin
Argumentos
Tipos de datos
This section lists thecom.Kameleoon.Data types supported by Kameleoon. Several standard data types are provided, as well as the CustomData type for defining custom data types.
Conversion
El conjunto de datosConversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
- Java
- Kotlin
Device
Since Android SDK
4.13.0, the Device is automatically detected based on the android.content.Context. However, you can still manually override it if needed.- Java
Geolocation
Geolocation contains the visitor’s geolocation details.
- Java
- Kotlin
CustomData
Define your own custom data types in the Kameleoon app or the Data API and use them from the SDK.- The index of the custom data is available in the Custom data configuration page of the Kameleoon app. Be careful: this index starts at 0, so the first custom data you create for a given site would have the index 0, not 1.
- Adding a
CustomDatainstance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
- Java
- Kotlin
Returned Types
DataFile
ElDataFile contiene los detalles de configuración del SDK.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
- Java
- Kotlin
FeatureFlag
FeatureFlag representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus Variations, Rules, estado del entorno y otros detalles relacionados.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
- Java
- Kotlin
Rule
Rule representa un conjunto de propiedades que definen una regla en sí — por ejemplo, sus Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
- Java
- Kotlin
Variation
Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
- The
Variationobject provides details about the assigned variation and its associated experiment, while theVariableobject contains specific details about each variable within a variation. - Ensure that your code handles the case where
idorexperimentIdmay benull, indicating a default variation. - The
variablesmap might be empty if no variables are associated with the variation.
- Java
- Kotlin
Variable
Variable contains information about a variable associated with the assigned variation.
- Java
- Kotlin
Deprecated methods
getFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
Use
getVariation() instead.featureKey como argumento obligatorio para recuperar la clave de variación para el usuario especificado.
If the visitor has never been associated with this feature flag, the SDK returns a randomly assigned variation key (according to the feature flag rules). If the visitor is already registered with this feature flag, this method returns the previous variation key. If the user does not match any of the rules, the default value will be returned, which is defined in your customer’s account.
Ensure you set up proper error handling como se muestra en el ejemplo code to catch potential exceptions.
- Java
- Kotlin
getFeatureVariationKey()
- 📨 Envía datos de seguimiento a Kameleoon
Use
getVariation() instead.featureKey como argumento obligatorio para recuperar la clave de variación para el usuario especificado.
If the visitor has never been associated with this feature flag, the SDK returns a randomly assigned variation key (according to the feature flag rules). If the visitor is already registered with this feature flag, this method returns the previous variation key. If the user does not match any of the rules, the default value will be returned, which is defined in your customer’s account.
Ensure you set up proper error handling como se muestra en el ejemplo code to catch potential exceptions.
- Java
- Kotlin
getActiveFeatures()
- Use
getVariations()instead. - Previously called
getFeatureListForVisitorCode, which was removed in SDK version4.0.0release.
getActiveFeatures method retrieves information about the active feature flags that are available for the visitor.
- Java
- Kotlin
Valor de retorno
getFeatureVariable()
- 📨 Envía datos de seguimiento a Kameleoon
Use
getVariation() instead.featureKey y un variableKey como argumentos obligatorios.
If the visitor has never been associated with the featureKey, the SDK returns a randomly assigned variable value for the specified variation key (according to the feature flag rules). If the visitor is already registered with this feature flag, the method returns the variable value for the previously registered variation. If the user does not match any of the rules, the default variable value is returned.
Ensure you set up proper error handling como se muestra en el ejemplo code to catch potential exceptions.
- Java
- Kotlin
Argumentos
Valor de retorno
Excepciones lanzadas
getFeatureVariationVariables()
- Use
getVariation()instead. - This method was previously called
getFeatureAllVariables, which was removed in SDK version4.0.0release.
featureKey. It returns the data as a Map<String, Object> type, as defined in the Kameleoon app. It throws an exception (FeatureNotFound) if the requested feature was not found in the SDK’s internal configuration.
- Java
- Kotlin
Argumentos
Valor de retorno
Excepciones lanzadas
getFeatureList()
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.- Java
- Kotlin