Usage examples

Library initialization 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.

Step 1. (Optional) Initialize a reporter with an extended configuration

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

Step 2. Configure sending data using a reporter

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, manually configure the reporters to send events about the start and the pause of the session for each reporter. Use the resumeSession() and pauseSession() methods in the IReporter interface when implementing onResume() and onPause() for 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

Tracking 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

Note.

Starting with Android AppMetrica SDK 5.0.0, sending device location data is disabled by default.

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

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

YandexMetrica.setLocationTracking(true);
Copied to clipboard
To determine the location more precisely, add to the AndroidManifest.xml file one of the following permissions:

Setting location manually

Before sending custom information about the device location, make sure that reporting is enabled.

The library determines the device location on its own. 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 location detection by the library, pass the null value to the YandexMetrica.setLocation(Location location) method and configure sending the device location data.

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\"}";

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 Events.

Sending an event from the WebView's JavaScript code

The AppMetrica SDK lets you send client events from JavaScript code. Initialize the sending by calling the initWebViewReporting method:

WebView webView = (WebView) findViewById(R.id.myWebView);
// do your initialization here
webView.getSettings().setJavaScriptEnabled(true);
YandexMetrica.initWebViewReporting(webView);
webView.loadUrl(myURL);
Copied to clipboard

Call the initWebViewReporting method after calling the setJavaScriptEnabled method but before calling loadUrl.

To send an event from JavaScript code, use the reportEvent(name, value) method in the AppMetrica interface:

function buttonClicked() {
  AppMetrica.reportEvent('Button clicked!', '{}');
})
Copied to clipboard

Arguments of the reportEvent method:

  • name — A string. Can't be null or empty.
  • value — A JSON string. Can be null.

Sending an error message

Example with groupIdentifier

If you send errors using methods with groupIdentifier, they are grouped by ID.

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

Don't use variable values as grouping IDs. Otherwise, the number of groups increases and it becomes difficult to analyze them.

Example with message

If errors are sent using the YandexMetrica.reportError(String message, Throwable error) method, they're grouped by stack trace.

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

Sending ProfileId

If you know the user profile ID before initializing the AppMetrica SDK, pass it before initialization (setUserProfileID) or during initialization with the extended configuration (withUserProfileID).

Otherwise, a user profile is created with the ID appmetrica_device_id.

Attention. AppMetrica doesn't display predefined attributes in the web interface if ProfieId sending isn't configured.

You can update ProfileId at any time by calling setUserProfileID:

YandexMetrica.setUserProfileID("id");
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 E-commerce events

In AppMetrica, it is not possible to segment E-commerce events into “test” and “not test”. If you use the main API key for debugging purchases, the test events are included in general statistics. If you need to debug sending E-commerce events, use a reporter to send statistics to an additional API key.

Step 1. Configure sending E-commerce events to the test API key

For different user actions, there are appropriate types of E-commerce events. To create a specific event type, use the appropriate ECommerceEvent class method.

The examples below show how to send specific types of events (Java):

Opening a page
Map<String, String> payload = new HashMap<>();
payload.put("configuration", "landscape");
payload.put("full_screen", "true"); 
// Creating a screen object.
  ECommerceScreen screen = new ECommerceScreen()
	.setCategoriesPath(Arrays.asList( // Optional.
		"Акции", 
		"Красная цена" 
	)) 
	.setName("ProductCardActivity") // Optional.
	.setSearchQuery("даниссимо кленовый сироп") // Optional.
	.setPayload(payload); // Optional.
  ECommerceEvent showScreenEvent = ECommerceEvent.showScreenEvent(screen);
// Sending an e-commerce event.
  YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportECommerce(showScreenEvent);
Viewing a product profile
Map<String, String> payload = new HashMap<>();
payload.put("configuration", "landscape");
payload.put("full_screen", "true"); 
// Creating a screen object.
  ECommerceScreen screen = new ECommerceScreen()
	.setCategoriesPath(Arrays.asList( // Optional.
		"Акции", 
		"Красная цена" 
	)) 
	.setName("ProductCardActivity") // Optional.
	.setSearchQuery("даниссимо кленовый сироп") // Optional.
	.setPayload(payload); // Optional.
// Creating an actualPrice object.
  ECommercePrice actualPrice = new ECommercePrice(new ECommerceAmount(4.53, "USD"))
	.setInternalComponents(Arrays.asList( // Optional. 
	new ECommerceAmount(30_570_000, "wood"), 
  new ECommerceAmount(26.89, "iron"), 
  new ECommerceAmount(new BigDecimal(5.1), "gold") 
	));
// Creating an originalPrice object.
  ECommercePrice originalPrice = new ECommercePrice(new ECommerceAmount(5.78, "USD"))
	.setInternalComponents(Arrays.asList( // Optional.
	new ECommerceAmount(30_590_000, "wood"),
  new ECommerceAmount(26.92, "iron"),
  new ECommerceAmount(new BigDecimal(5.5), "gold") 
	));
// Creating a product object. 
  ECommerceProduct product = new ECommerceProduct("779213")
	.setActualPrice(actualPrice) // Optional.
	.setPromocodes(Arrays.asList("BT79IYX", "UT5412EP")) // Optional.
	.setPayload(payload) // Optional.
	.setOriginalPrice(originalPrice) // Optional.
	.setName("Продукт творожный «Даниссимо» 5.9%, 130 г.") // Optional.
	.setCategoriesPath(Arrays.asList("Продукты", "Молочные продукты", "Йогурты")); // Optional.
                      ECommerceEvent showProductCardEvent = ECommerceEvent.showProductCardEvent(product, screen);
// Sending an e-commerce event.
  YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportECommerce(showProductCardEvent);
Copied to clipboard
Viewing a product page
Map<String, String> payload = new HashMap<>();
payload.put("configuration", "landscape");
payload.put("full_screen", "true"); 
// Creating a screen object.
  ECommerceScreen screen = new ECommerceScreen()
	.setCategoriesPath(Arrays.asList( // Optional.
		"Акции", 
		"Красная цена" 
	)) 
	.setName("ProductCardActivity") // Optional.
	.setSearchQuery("даниссимо кленовый сироп") // Optional.
	.setPayload(payload); // Optional.

// Creating an actualPrice object.
  ECommercePrice actualPrice = new ECommercePrice(new ECommerceAmount(4.53, "USD"))
	.setInternalComponents(Arrays.asList( // Optional. 
	new ECommerceAmount(30_570_000, "wood"), 
  new ECommerceAmount(26.89, "iron"), 
  new ECommerceAmount(new BigDecimal(5.1), "gold") 
	));
// Creating an originalPrice object.
  ECommercePrice originalPrice = new ECommercePrice(new ECommerceAmount(5.78, "USD"))
	.setInternalComponents(Arrays.asList( // Optional.
	new ECommerceAmount(30_590_000, "wood"),
  new ECommerceAmount(26.92, "iron"),
  new ECommerceAmount(new BigDecimal(5.5), "gold") 
	));
// Creating a product object. 
  ECommerceProduct product = new ECommerceProduct("779213")
	.setActualPrice(actualPrice) // Optional.
	.setPromocodes(Arrays.asList("BT79IYX", "UT5412EP")) // Optional.
	.setPayload(payload) // Optional.
	.setOriginalPrice(originalPrice) // Optional.
	.setName("Продукт творожный «Даниссимо» 5.9%, 130 г.") // Optional.
	.setCategoriesPath(Arrays.asList("Продукты", "Молочные продукты", "Йогурты")); // Optional.
// Creating a referrer object.
  ECommerceReferrer referrer = new ECommerceReferrer()
	.setType("button") // Optional.
	.setIdentifier("76890") // Optional.
	.setScreen(screen); // Optional.
                      ECommerceEvent showProductDetailsEvent = ECommerceEvent.showProductDetailsEvent(product, referrer); // Referrer is optional — can be null.
// Sending an e-commerce event.
  YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportECommerce(showProductDetailsEvent);
Copied to clipboard
Adding or removing an item to/from the cart
Map<String, String> payload = new HashMap<>();
payload.put("configuration", "landscape");
payload.put("full_screen", "true"); 
// Creating a screen object.
  ECommerceScreen screen = new ECommerceScreen()
	.setCategoriesPath(Arrays.asList( // Optional.
		"Акции", 
		"Красная цена" 
	)) 
	.setName("ProductCardActivity") // Optional.
	.setSearchQuery("даниссимо кленовый сироп") // Optional.
	.setPayload(payload); // Optional.
// Creating an actualPrice object.
  ECommercePrice actualPrice = new ECommercePrice(new ECommerceAmount(4.53, "USD"))
	.setInternalComponents(Arrays.asList( // Optional. 
	new ECommerceAmount(30_570_000, "wood"), 
  new ECommerceAmount(26.89, "iron"), 
  new ECommerceAmount(new BigDecimal(5.1), "gold") 
	));
// Creating an originalPrice object.
  ECommercePrice originalPrice = new ECommercePrice(new ECommerceAmount(5.78, "USD"))
	.setInternalComponents(Arrays.asList( // Optional.
	new ECommerceAmount(30_590_000, "wood"),
  new ECommerceAmount(26.92, "iron"),
  new ECommerceAmount(new BigDecimal(5.5), "gold") 
	));
// Creating a product object. 
  ECommerceProduct product = new ECommerceProduct("779213")
	.setActualPrice(actualPrice) // Optional.
	.setPromocodes(Arrays.asList("BT79IYX", "UT5412EP")) // Optional.
	.setPayload(payload) // Optional.
	.setOriginalPrice(originalPrice) // Optional.
	.setName("Продукт творожный «Даниссимо» 5.9%, 130 г.") // Optional.
	.setCategoriesPath(Arrays.asList("Продукты", "Молочные продукты", "Йогурты")); // Optional.
// Creating a referrer object.
  ECommerceReferrer referrer = new ECommerceReferrer()
	.setType("button") // Optional.
	.setIdentifier("76890") // Optional.
	.setScreen(screen); // Optional.
// Creating a cartItem object. 
  ECommerceCartItem addedItems1 = new ECommerceCartItem(product, actualPrice, 1.0)
	.setReferrer(referrer); // Optional.
                      ECommerceEvent addCartItemEvent = ECommerceEvent.addCartItemEvent(addedItems1);
                      // Sending an e-commerce event.
  YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportECommerce(addCartItemEvent);
                      ECommerceEvent removeCartItemEvent = ECommerceEvent.removeCartItemEvent(addedItems1);
// Sending an e-commerce event.
  YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportECommerce(removeCartItemEvent);
Copied to clipboard
Starting and completing a purchase
Map<String, String> payload = new HashMap<>();
payload.put("configuration", "landscape");
payload.put("full_screen", "true"); 
// Creating a screen object.
  ECommerceScreen screen = new ECommerceScreen()
	.setCategoriesPath(Arrays.asList( // Optional.
		"Акции", 
		"Красная цена" 
	)) 
	.setName("ProductCardActivity") // Optional.
	.setSearchQuery("даниссимо кленовый сироп") // Optional.
	.setPayload(payload); // Optional.
// Creating an actualPrice object.
  ECommercePrice actualPrice = new ECommercePrice(new ECommerceAmount(4.53, "USD"))
	.setInternalComponents(Arrays.asList( // Optional. 
	new ECommerceAmount(30_570_000, "wood"), 
  new ECommerceAmount(26.89, "iron"), 
  new ECommerceAmount(new BigDecimal(5.1), "gold") 
	));
// Creating an originalPrice object.
  ECommercePrice originalPrice = new ECommercePrice(new ECommerceAmount(5.78, "USD"))
	.setInternalComponents(Arrays.asList( // Optional.
	new ECommerceAmount(30_590_000, "wood"),
  new ECommerceAmount(26.92, "iron"),
  new ECommerceAmount(new BigDecimal(5.5), "gold") 
	));
// Creating a product object. 
  ECommerceProduct product = new ECommerceProduct("779213")
	.setActualPrice(actualPrice) // Optional.
	.setPromocodes(Arrays.asList("BT79IYX", "UT5412EP")) // Optional.
	.setPayload(payload) // Optional.
	.setOriginalPrice(originalPrice) // Optional.
	.setName("Продукт творожный «Даниссимо» 5.9%, 130 г.") // Optional.
	.setCategoriesPath(Arrays.asList("Продукты", "Молочные продукты", "Йогурты")); // Optional.
// Creating a referrer object.
  ECommerceReferrer referrer = new ECommerceReferrer()
	.setType("button") // Optional.
	.setIdentifier("76890") // Optional.
	.setScreen(screen); // Optional.
// Creating a cartItem object. 
  ECommerceCartItem addedItems1 = new ECommerceCartItem(product, actualPrice, 1.0)
	.setReferrer(referrer); // Optional.
// Creating an order object.
ECommerceOrder order = new ECommerceOrder("88528768", Arrays.asList(addedItems1))
        .setPayload(payload); // Optional.
                      ECommerceEvent beginCheckoutEvent = ECommerceEvent.beginCheckoutEvent(order);
// Sending an e-commerce event.
  YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportECommerce(beginCheckoutEvent);
                      ECommerceEvent purchaseEvent = ECommerceEvent.purchaseEvent(order);
// Sending an e-commerce event.
  YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportECommerce(purchaseEvent);
Copied to clipboard

Step 2. Check the test application's report

Make in-app test purchases. After a while, check the “Purchase analysis” report in the AppMetrica interface. Make sure that the report shows E-commerce events.

For more information about the report, see Purchase analysis.

Step 3. Configure sending events to the main API key

After successful testing, configure sending E-commerce events to the main API key.

To send the ECommerceEvent instance to the main API key, use the YandexMetrica.reportECommerce(@NonNull ECommerceEvent event) method.

...
// Sending an e-commerce event.
YandexMetrica.reportECommerce(ecommerceEvent);
Copied to clipboard

Sending Revenue

AppMetrica supports the validation of purchases made using the Google Play Billing library. Validation lets you filter purchases made from hacked apps. If validation is enabled and a purchase fails it, this purchase isn't shown in reports.

Note. Local validation with a public key is used to validate purchases on Android. To enable validation, create a public key and specify it in the settings. For more information, see Sending In-App purchases on Android.

Step 1. Configure sending Revenue to the test API key

AppMetrica doesn't let you segment Revenue into “test” and “not test”. If you use the main API key for debugging purchases, the test purchases are included in general statistics. If you need to debug sending Revenue, use a reporter to send statistics to an additional API key.

This section outlines the steps for sending Revenue to the additional API key:

To validate purchases on Android, configure sending the Revenue.Receipt instance along with the Revenue:

  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 to the test API key using the IReporter. For more information about reporters, see Usage examples.
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 using reporter.
    YandexMetrica.getReporter(getApplicationContext(), "Testing API key").reportRevenue(revenue);
}
Copied to clipboard

Step 2. Check the test application's report

In the AppMetrica interface, check the “Revenue” report. Make sure that the number of purchases has increased.

For more information about the report, see Revenue.

Step 3. Configure sending Revenue to the main API key

After successful testing, configure sending Revenue to the main API key.

To send the Revenue instance to the main API key, use the YandexMetrica.reportRevenue(Revenue revenue) method.

...
// 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 file build.gradle.

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

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

Tracking app openings using deeplinks

To track app openings that use deeplinks, you make changes in the Activity that handles deeplinks. You need to track app openings to correctly track 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(intent);
    }
}
Copied to clipboard
Note. You can add the opening of the app via the deferred deeplink on Android.

Requesting a deferred deeplink

To request a deferred deeplink, pass a class instance that implements the DeferredDeeplinkListener interface to the YandexMetrica.requestDeferredDeeplink(DeferredDeeplinkListener listener) method. The method returns the deferred deeplink only at the initial application start after obtaining the Google Play Install Referrer.

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.requestDeferredDeeplink(new DeferredDeeplinkListener() {
    @Override
    public void onDeeplinkLoaded(String deeplink) {
        Log.i("Deeplink", "deeplink = " + deeplink);
    }

    @Override
    public void onError(Error error, String referrer) {
        Log.i("Deeplink", "Error: " + error.getDescription() + ", unparsed referrer: " + referrer);
    }
});
Copied to clipboard

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

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, when the app is first launched, all users are identified as new. If the AppMetrica SDK connects to an app that already has active users, you can configure it for new and old users to track statistics correctly. 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

Alert example

You can use any text to inform users of statistics collection. For example:

This app uses the AppMetrica analytical service (Yandex Metrica for apps) provided by YANDEX LLC, ulitsa Lva Tolstogo 16, Moscow, Russia 119021 (hereinafter referred to as Yandex) based on the Terms of Use.

AppMetrica analyzes app usage data, including the device it is running on, the installation source, calculates conversion, collects statistics of your activity for product analytics, ad campaign analysis, and optimization, as well as for troubleshooting. Information collected in this way cannot identify you.

Depersonalized information about your use of this app collected by AppMetrica tools will be transferred to Yandex and stored on Yandex’s server in the EU and the Russian Federation. Yandex will process this information to assess how you use the app, compile reports for us on our app operation, and provide other services.

If you didn't find the answer you were looking for, you can use the feedback form to submit your question. Please describe the problem in as much detail as possible. Attach a screenshot if possible.