Installation and initialization

Attention.

This is an archived version of documentation. You can find the current documentation for all platforms here.

The SDK for Android is an AAR library. The library is available in the Maven repository.

This section describes the steps to enable and initialize AppMetrica SDK:

  1. Step 1. Add the library to your project
  2. Step 2. Initialize the library
  3. Step 3. (Optional) Configure location detection
  4. Step 4. (Optional) Configure sending events, profile attributes, and Revenue
  5. Step 5. Test the library operation

Step 1. Add the library to your project

If you use Gradle for building the app, add this dependency to the build.gradle file:

dependencies {
    // AppMetrica SDK.
    implementation 'com.yandex.android:mobmetricalib:5.3.0'
}
Copied to clipboard

Step 2. Initialize the library

Attention. You should take into account some features of the AppMetrica library during initialization. For more information, see Features of the AppMetrica library.

Initialize the library in the app and set up user activity tracking. Extend the Application class and override the onCreate() method as follows:

public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // Creating an extended library configuration.
        YandexMetricaConfig config = YandexMetricaConfig.newConfigBuilder(API_key).build();
        // Initializing the AppMetrica SDK.
        YandexMetrica.activate(getApplicationContext(), config);
        // Automatic tracking of user activity.
        YandexMetrica.enableActivityAutoTracking(this);
        }
}
Copied to clipboard
What is the API key?

The API key is a unique application identifier that is issued in the AppMetrica web interface during app registration.

Make sure you have entered it correctly.

AppMetrica allows tracking pre-installed apps. To use this feature, you should initialize the library with the extended configuration.

Optional

When using Firebase Performance Monitoring in Firebase version 31.0.0+, activate FirebaseApp for all processes, including the AppMetrica SDK process. In Application#onCreate(), call FirebaseApp.initializeApp(this) before activating the AppMetrica SDK. Otherwise, the AppMetrica SDK won't be activated.

Example:

class MainApplication : Application() {
    
    override fun onCreate() {
        super.onCreate()
        
        // Init FirebaseApp for all processes
        FirebaseApp.initializeApp(this)
        
        // Then activate AppMetrica SDK
        YandexMetrica.activate(
            this,
            YandexMetricaConfig.newConfigBuilder(API_KEY)
                .build()
        )
    }
}

Step 3. (Optional) Configure location detection

Location allows you to estimate the geographical distribution of users. By default, AppMetrica determines the device location by the IP address with accuracy to the country.

To determine the device location down to the city level, open the AndroidManifest.xml file and add the uses-permission element before the application element:

<manifest>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <application>...</application>
</manifest>
Copied to clipboard

ACCESS_COARSE_LOCATION allows you to track the device's location. For more information, see Android documentation.

Step 4. (Optional) Configure sending events, profile attributes, and Revenue

To collect information on user actions in the app, set up sending your own events. For more information, see Sending your own events.

To collect information about users, set up sending profile attributes. For more information, see Profiles.

Note. Unlike events, a profile attribute can take only one value. When you send a new attribute value, the old value is overwritten.

To track in-app purchases, set up Revenue sending. For more information, see In-App purchases.

Step 5. Test the library operation

Attention. Before testing the library, ensure that the SDK is initialized in compliance with recommendations.
To test how the library works:
  1. Start the app with the AppMetrica SDK and use it for a while.
  2. Make sure your device is connected to the internet.
  3. In the AppMetrica interface, make sure that:
    • There is a new user in the Audience report.
    • The number of sessions in the Engagement → Sessions report has increased.
    • There are events and profile attributes in the Events and Profiles reports.

Troubleshooting

The number of sessions does not increase

Check your session tracking settings. For more information, see Tracking user activity.

There are no events in the report
  1. Perform a minimum of 10 app actions that trigger the event sending.

    It's necessary because AppMetrica accumulates events in the buffer and sends to the server in several parts.

  2. Wait for 10 minutes and check the report. Reports don't display events immediately.
Error when adding the library to a project
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502)
at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491)
at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.run(Main.java:246)
at com.android.dx.command.dexer.Main.main(Main.java:215)
at com.android.dx.command.Main.main(Main.java:106)

This error indicates that the method limit was exceeded at the DexIndexOverflowException stage of processing. We recommend reviewing the libraries used — perhaps they are very heavy. If they can't be replaced with lightweight alternatives, you can use multiple DEX files. This might increase the app loading time.

Error initializing AppMetrica with third-party libraries

The code in the Application.onCreate() method runs for all processes. If you encounter an initialization error after integrating a third-party library (such as Firebase Cloud Messaging), make sure that the third-party library is initialized only in the main process.

Error examples:

  • Unable to create application your.package.name.YourApp: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process your.package.name:Metrica. Make sure to call FirebaseApp.initializeApp(Context) first.
  • android.database.sqlite.SQLiteException: table httpauth already exists (code 1)
  • Fatal Exception: java.lang.RuntimeException: Using WebView from more than one process at once with the same data directory is not supported.
  • ANR at com.google.android.gms.ads.*

To fix the error, implement the main process check before initializing third-party libraries:

class MyApplication extends Application {
    @Override
    public void onCreate() {
        if (isMainProcess()) {
            // Initializing third-party libraries after verification.
        }
    }
}
Copied to clipboard
Note. Implement verification of the main process on your own. See an example in the Stack Overflow answer.
Incorrect duration of user session during manual tracking

If the manual tracking of the user session is incorrectly implemented, it may lead to an inaccurate determination of its duration.

If the user session duration data doesn't look correct, make sure that when the user session ends, the YandexMetrica.pauseSession() method is always called. If this method is not called, the library considers that the session is active and commits regular data exchange with the server part of AppMetrica.

It is recommended to check the duration of the session timeout. It is specified with the withSessionTimeout() method. The timeout specifies the time interval during which the session will be considered active even after the application is closed.

High power consumption of the AppMetrica library

If there is the increased power consumption of the library, make sure that when the user session ends, the YandexMetrica.pauseSession() method is always called. If this method is not called, the library considers that the session is active and commits regular data exchange with the server part of AppMetrica.

It is recommended to check the duration of the session timeout. It is specified with the withSessionTimeout() method. The timeout specifies the time interval during which the session will be considered active even after the application is closed.

My problem is not listed
If your problem is not listed, contact support service. Specify the following:
  1. The source code snippet that shows the SDK integration to your app.
  2. Application ID in the AppMetrica web interface.
  3. Device ID.
    How to get the Google AID
    1. Install the AppMetrica app on the test device.
    2. Log in and select your app from the list.
    3. In the upper-left corner, click  → Device Management.
    4. The Google AID is shown in the AID field. Enter it in the AppMetrica web interface.
    Note. You can enable attribution testing in the AppMetrica app. To do this, turn on Attribution testing.
  4. Device model and manufacturer, platform and OS version, AppMetrica SDK version.

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.