Usage examples

Initializing the library with the extended configuration

To initialize the library with the extended startup configuration, create an instance of the YandexMetricaConfig class with appropriate settings and activate the library using the YandexMetrica.activate(Context context, YandexMetricaConfig config) method. With the extended configuration allows you to enable/disable logging, set session timeout, pass parameters for tracking pre-installed apps, and so on.

The parameters of the extended configuration are applied from the time of library initialization.

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // Creating an extended library configuration.
        YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
                // Setting up the configuration. For example, to enable logging.
                .withLogs()
                ...
                .build();
        // Initializing the AppMetrica SDK.
        YandexMetrica.activate(getApplicationContext(), config);
        // Automatic tracking of user activity.
        YandexMetrica.enableActivityAutoTracking(this);
    }
}
Copied to clipboard

To configure the library while the application is running, use the methods of the YandexMetrica class.

Sending statistics to an additional API key

Sending data to an additional API key allows you to collect own statistics for these API keys. You can use this to control access to information for other users. For example, to provide access to statistics for analysts you can duplicate sending marketing data for the additional API key. Thus they will only have access to the information they need.

To send data to an additional API key, you must use reporters. Just like for the main API key, you can set up an extended startup configuration for a reporter, send events, profile information, and data about in-app purchases. The reporter can work without the AppMetrica SDK initialization.

To initialize a reporter with the extended configuration, create an object of the ReporterConfig class with the necessary settings and activate the reporter using the YandexMetrica.activateReporter(Context context, ReporterConfig config) method. This configuration is used for a reporter with the specified API key. You can set up your own configuration for each additional API key.
Attention. The reporter with the extended configuration should be initialized before the first call to the reporter. Otherwise, the reporter will be initialized without a configuration.
// Creating extended configuration of the reporter.
// To create it, pass an API_key that is different from the app's API_key.
ReporterConfig reporterConfig = ReporterConfig.newConfigBuilder(API_key)
        // Setting up the configuration. For example, to enable logging.
        .withLogs()
        ...
        .build();
// Initializing a reporter.
YandexMetrica.activateReporter(getApplicationContext(), reporterConfig);
Copied to clipboard

To send data using a reporter, you must get an object that implements the IReporter interface by the YandexMetrica.getReporter(Context context, String apiKey) method and use the interface methods to send reports. If the reporter was not initialized with the extended configuration, calling this method will initialize the reporter for the specified API key.

Example of sending an event:

YandexMetrica.getReporter(getApplicationContext(), API_key).reportEvent("Updates installed");
Copied to clipboard
For correct tracking, the reporters should be manually configured to send events about the start and the pause of the session for each reporter. Use the methods resumeSession(Activity activity) and pauseSession(Activity activity) of the IReporter interface in the implementation onResume() and onPause() of your Activity:
public class YourActivity extends Activity {
    ...
    @Override
    protected void onResume() {
        super.onResume();
        YandexMetrica.getReporter(getApplicationContext(), API_key).resumeSession();
    }

    @Override
    protected void onPause() {
        YandexMetrica.getReporter(getApplicationContext(), API_key).pauseSession();
        super.onPause();
    }
    ...
}
Copied to clipboard

Monitoring app crashes

Reports on app crashes are sent by default.

To disable automatic monitoring, initialize the library with the configuration in which sending crashes is disabled. To do this, pass the false value to the withLocationTracking(boolean enabled) method when creating the extended library configuration.

// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        // Disabling the data sending about the app crashes.
        .withCrashReporting(false)
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);

If automatic monitoring is disabled, you can manually submit information about crashes.

Manually monitoring app crashes

Reports on app crashes are sent by default. To avoid exception events duplication, disable the automatic monitoring of the app crashes.

To send crash information manually, use the YandexMetrica.reportUnhandledException(Throwable exception) method.

final Thread.UncaughtExceptionHandler previousUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
// Creating a new handler.
Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread thread, Throwable exception) {
        try {
            // Sending a message about an app crash to the AppMetrica server.
            YandexMetrica.reportUnhandledException(exception);
        } finally {
            // Sending a message about an app crash to the system handler.
            if (previousUncaughtExceptionHandler != null) {
                previousUncaughtExceptionHandler.uncaughtException(thread, exception);
            }
        }
    }
};
// Setting the default handler.
Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
Copied to clipboard

Monitoring native app crashes

Reports are sent automatically on native app crashes if the library's SO files are added to the project. By default, SO files are omitted. To add them, enable the library for tracking native crashes.

To enable the library, add the following dependency to the build.gradle file in the dependencies block:

dependencies {
    ...
    implementation 'com.yandex.android:mobmetricalib-ndk-crashes:1.1.0'
}
Copied to clipboard
If you don't use Gradle

Download the library and add it to the project.

It contains libraries for all the platforms (arm, armv7, mips, x86). Use abi splits to exclude unnecessary libraries.

To disable automatic monitoring, initialize the library with the configuration in which sending crashes is disabled. To do this, pass the false value to the withNativeCrashReporting(boolean enabled) method when creating the extended library configuration.

// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        // Disabling the data sending about the native app crashes.
        .withNativeCrashReporting(false)
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);
Copied to clipboard

If automatic monitoring is disabled, you can manually submit information about native crashes.

Monitoring native app crashes manually

Reports are sent automatically on native app crashes if the library's SO files are added to the project. If files have been added, you should disable the automatic monitoring of the app crashes to avoid exception events duplication.

To manually send information about native app crashes, use the YandexMetrica.reportNativeCrash(String nativeCrash) method.

String nativeCrashContent =
"...\n" + 
"400ae000-400b7000 r-xp 00000000 103:0c 835       /system/lib/libcutils.so\n" + 
"400b7000-400b8000 r--p 00008000 103:0c 835       /system/lib/libcutils.so\n" +
"400b8000-400b9000 rw-p 00009000 103:0c 835       /system/lib/libcutils.so\n" +
"400b9000-400bc000 r-xp 00000000 103:0c 1454      /system/lib/liblog.so\n" +
"...";
// Sending native app crash information.
YandexMetrica.reportNativeCrash(nativeCrashContent);
Copied to clipboard

Sending the device location by the library

By default, sending the device location in library reports is enabled. To determine the location more precisely, add to the AndroidManifest.xml file one of the following permissions:

AppMetrica allows you to manage sending reports about the device location. When you disable sending the user location, it also turns off all other methods to locate the device (including locating by IP address) in the AppMetrica SDK. Users who have the option to send location data disabled are grouped together in the geographic report with the “Undefined” value as the region name.

The option to send location data is enabled by default.

To disable sending, initialize the library with the configuration where sending device location option is disabled. To do this, pass the false value to the withLocationTracking(boolean enabled) method when creating the extended library configuration.
// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        // Disabling the data sending about the device location.
        .withLocationTracking(false)
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);
Copied to clipboard

To disable sending while the app is running, use the YandexMetrica.setLocationTracking(boolean enabled) method:

YandexMetrica.setLocationTracking(false);
Copied to clipboard

Setting location manually

Before sending custom information on the location of the device, make sure that the reporting is not disabled.

By default, the device location is detected by the library. To send your own device location information, pass an instance of the android.location.Location class into the YandexMetrica.setLocation(Location Location) method.

// Determining the location.
Location currentLocation = ...;
// Setting your own location information of the device.
YandexMetrica.setLocation(currentLocation);
Copied to clipboard
To send your own device location information using the startup configuration, pass the android.location.Location instance to the withLocation(Location Location) method when creating the extended library configuration.
// Determining the location.
Location currentLocation = ...;

// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        // Set your own location information of the device.
        .withLocation(currentLocation)
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);
Copied to clipboard

To resume the location detection by the library, pass to the YandexMetrica.setLocation(Location Location) method the null value:

YandexMetrica.setLocation(null);
Copied to clipboard

Sending a custom event

To send your custom event without nested parameters, pass a short name or description of the event to the YandexMetrica.reportEvent(String eventName) method:

YandexMetrica.reportEvent("Updates installed");
Copied to clipboard

Sending a custom event with nested parameters

The AppMetrica SDK allows you to send your own events with nested parameters that can be set in the JSON format or as a set of attributes (Map).

To pass nested event parameters in the JSON format, use the YandexMetrica.reportEvent(String eventName, String jsonValue) method:

String eventParameters = "{\"name\":\"Alice\", \"age\":\"18\", \"favorite_games\":{\"strategies\":\"Age of Empires\"}}";

YandexMetrica.reportEvent("New person", eventParameters);
Copied to clipboard

The AppMetrica web interface displays up to five nesting levels for events. So if an event has six or more levels, only the top five are shown in the report. You can use the Reporting API to get up to ten levels.

For more information about events, see Sending your own events.

Sending an error message

To send your own error message, pass a description (message) and an error class (error) to the YandexMetrica.reportError(String message, Throwable error) method:

try {
    Integer.valueOf("00xffWr0ng");
} catch (Throwable error) {
    YandexMetrica.reportError("Error while parsing some integer number", error);
}
Copied to clipboard

Sending profile attributes

To send profile attributes, pass to the instance of the UserProfile class required attributes and send this instance using the YandexMetrica.reportUserProfile(UserProfile profile) method. To create profile attributes, use methods of the Attribute class.

// Creating the UserProfile instance.
UserProfile userProfile = UserProfile.newBuilder()
        // Updating predefined attributes.
        .apply(Attribute.name().withValue("John"))
        .apply(Attribute.gender().withValue(GenderAttribute.Gender.MALE))
        .apply(Attribute.birthDate().withAge(24))
        .apply(Attribute.notificationsEnabled().withValue(false))
        // Updating custom attributes.
        .apply(Attribute.customString("string_attribute").withValue("string"))
        .apply(Attribute.customNumber("number_attribute").withValue(55))
        .apply(Attribute.customCounter("counter_attribute").withDelta(1))
        .build();
// Setting the ProfileID using the method of the YandexMetrica class.
YandexMetrica.setUserProfileID("id");

// Sending the UserProfile instance.
YandexMetrica.reportUserProfile(userProfile);
Copied to clipboard

Sending Revenue

You can validate Google Play in-app purchases. Validation is necessary to filter out purchases that were made from hacked apps. This is important for game apps.

Currently, AppMetrica does not support purchase validation. However, you can send validated purchases via the SDK.

To send purchase information with the validation, do the following in the handler for the purchase:
  1. Create the Revenue.Receipt instance with information about the purchase and signature. You must use it when creating the Revenue instance in Revenue.Builder.withReceipt (Revenue.Receipt receipt).
  2. Create the Revenue instance using the Revenue.Builder constructor.
  3. Send the Revenue instance using the YandexMetrica.reportRevenue(Revenue revenue) method.
void handlePurchase(Purchase purchase) {
    ...
    // Creating the Revenue.Receipt instance.
    // It is used for checking purchases in Google Play.
    Revenue.Receipt revenueReceipt = Revenue.Receipt.newBuilder()
            .withData(purchase.getOriginalJson())
            .withSignature(purchase.getSignature())
            .build();
    // Creating the Revenue instance.
    Revenue revenue = Revenue.newBuilderWithMicros(99000000, Currency.getInstance("RUB"))
            .withProductID("com.yandex.service.299")
            .withQuantity(2)
            .withReceipt(revenueReceipt)
            .withPayload("{\"source\":\"Google Play\"}")
            .build();
    // Sending the Revenue instance.
    YandexMetrica.reportRevenue(revenue);
}
Copied to clipboard

Setting the length of the session timeout

By default, the session timeout is 10 seconds. The minimum acceptable value for the sessionTimeout parameter is 10 seconds.

To change the length of the timeout, pass the value in seconds to the withSessionTimeout(int sessionTimeout) method when creating the extended library configuration.

// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        // Setting the length of the session timeout.
        .withSessionTimeout(15)
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);
Copied to clipboard

Setting the app version

By default, the app version is set in the AndroidManifest.xml file.

To specify the app version from the code, pass the app version to the withAppVersion(String appVersion) method when creating the extended library configuration.

// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        // Setting the app version.
        .withAppVersion("1.13.2")
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);
Copied to clipboard

where 1.13.2 is the app version.

Determining the library's API level

To determine the API level of the library from the application code, use the YandexMetrica.getLibraryApiLevel() method.
int libraryApiLevel = YandexMetrica.getLibraryApiLevel();
Copied to clipboard

Determining the library version

To determine the library version from the application code, use the YandexMetrica.getLibraryVersion() method:

String libraryVersion = YandexMetrica.getLibraryVersion();
Copied to clipboard

Tracking installation sources

The AppMetrica SDK uses Google Play INSTALL_REFERRER to track the source of app installs. To improve the quality of tracking, it is recommended to enable the Play Install Referrer library.

To enable the library, add the following dependency to the build.gradle file in the dependencies block:
dependencies {
    ...
    implementation 'com.android.installreferrer:installreferrer:1.0'
}
Copied to clipboard

Tracking installation source in AppMetrica SDK is enabled by default.

To disable tracking, make the following changes to the AndroidManifest.xml file:
<manifest
    ...
    xmlns:tools="http://schemas.android.com/tools">
    ...
    <application ...>
        ...
        <receiver android:name="com.yandex.metrica.MetricaEventHandler" tools:node="remove"/>
        ...
    </application>
</manifest>
Copied to clipboard

Simultaneous use of multiple tracking systems

When using multiple systems for installation source tracking at the same time, statistics might be incorrect. This happens because each tracking system adds its own INSTALL_REFERRER BroadcastReceiver. And some versions of Google Play only pass INSTALL_REFERRER to one of tracking systems. To resolve this problem, follow these steps:

  1. Add the main INSTALL_REFERRER BroadcastReceiver for the AppMetrica library in the AndroidManifest.xml file:
    <manifest ...>
        ...
        <application ...>
            ...
            <receiver
                android:name="com.yandex.metrica.MetricaEventHandler"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action android:name="com.android.vending.INSTALL_REFERRER"/>
                </intent-filter>
            </receiver>
            ...
        </application>
    </manifest>
    Copied to clipboard
  2. Register the INSTALL_REFERRER BroadcastReceiver of the other tracking systems in the library. To do this, use the method YandexMetrica.registerReferrerBroadcastReceivers(BroadcastReceiver... anotherReferrerReceivers):
    public void YourApplication extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            // Initializing the AppMetrica SDK.
            ...
            // Creating a BroadcastReceiver for INSTALL_REFERRER other tracking systems.
            AnotherReferrerReceiver anotherReferrerReceiver = new AnotherReferrerReceiver();
            // Registering INSTALL_REFERRER BroadcastReceiver created in Appmetrica.
            YandexMetrica.registerReferrerBroadcastReceivers(anotherReferrerReceiver);
            ...
        }
    }
    Copied to clipboard

The library will receive INSTALL_REFERRER, count it, and pass it to the other registered trackers. Thus, all the installation source trackers can count this INSTALL_REFERRER on equal terms.

If this option doesn't suit you, you can disable tracking INSTALL_REFERRER in the AppMetrica library and implement your own INSTALL_REFERRER BroadcastReceiver that will deliver INSTALL_REFERRER to all the tracking systems:

public class YourOwnReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Here you need to pass the Intent instance to other tracking systems.

        new MetricaEventHandler().onReceive(context, intent);
    }
}
Copied to clipboard

Tracking app openings via deeplinks

To track app openings that use deeplinks, you make changes in the Activity that handles deeplinks. Tracking app opening is necessary for correct tracking of the remarketing campaigns.

Note. To work with deeplinks, configure them in your application.

Use the reportAppOpen() method to track app openings:

public class DeeplinkActivity extends Activity {

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
        if (savedInstanceState == null) {
            YandexMetrica.reportAppOpen(this);
        }
    }
    @Override
    protected void onNewIntent(final Intent intent) {
        super.onNewIntent(intent);
        YandexMetrica.reportAppOpen(this);
    }
}
Copied to clipboard

Requesting deferred deeplink parameters

To request parameters for a deferred deeplink, pass to the YandexMetrica.requestDeferredDeeplinkParameters(DeferredDeeplinkParametersListener listener) method an instance that implements the DeferredDeeplinkParametersListener interface. The method returns the deferred deeplink parameters only at the first application start after Google Play Install Referrer obtaining.

Note. If Google Play Install Referrer is obtained immediately after installation, the system will not be able to properly recognize the first application launch.
YandexMetrica.requestDeferredDeeplinkParameters(new DeferredDeeplinkParametersListener() {
    @Override
    public void onParametersLoaded(Map<String, String> parameters) {
        // Processing deeplink parameters.
        for (String key : parameters.keySet()) {
            Log.i("Deeplink params", "key: " + key + " value: " + parameters.get(key));
        }
    }

    @Override
    public void onError(Error error, String referrer) {
        // Handling the error.
        Log.e("Error!", error.getDescription());
    }
});
Copied to clipboard

For more information about deferred deeplinks, see Support for deferred deeplinks

Tracking new users

By default, the user is counted as a new user when the app is opened for the first time. If you connect the AppMetrica SDK to an application that already has active users, you can set up tracking new users. To set this up, initialize the AppMetrica SDK with the extended configuration YandexMetricaConfig:

boolean isFirstLaunch;
// Implement logic to detect whether the app is opening for the first time.
// For example, you can check for files (settings, databases, and so on),
// which the app creates on its first launch.
if (conditions) {
    isFirstLaunch = true;
}
// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        .handleFirstActivationAsUpdate(!isFirstLaunch)
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);
Copied to clipboard

Disable and enable sending statistics

If you need confirmation from the user before sending statistical data, you should initialize the library with the disabled sending option. Pass the false value to the withStatisticsSending() method when creating the extended library configuration.

// Creating an extended library configuration.
YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key)
        // Disabling sending statistics.
        .withStatisticsSending(false)
        .build();
// Initializing the AppMetrica SDK.
YandexMetrica.activate(getApplicationContext(), config);
Copied to clipboard
After the user has confirmed to send statistics (for example, in the application settings or in the agreement on the first start of the app), you should call the YandexMetrica.setStatisticsSending(Context context, boolean enabled) method to enable it:
// Checking the status of the boolean variable. It shows the user confirmation.
if (flag) {
    // Enabling sending statistics.
    YandexMetrica.setStatisticsSending(getApplicationContext(), true);
}
Copied to clipboard