Android V2 V1

Integrate SDK into your Android project. As an example, use a ready-made demo app in Java.

Basic requirements

  • Oldest Android version supported – 4.0 (API Level 14).

  • Project must have Google Play Services enabled (com.google.android.gms:play-services-ads-identifier module).

  • If you publish an app to Huawei App Store, the project must have Huawei Media Services enabled (com.huawei.hms:hms-ads-identifier module), to myTracker can get Huawei OAID.

Integration

Using Gradle

Add build.gradle file to your project dependencies section:

dependencies {
//... other dependencies
implementation 'com.my.tracker:mytracker-sdk:1.5.+'
}

Manually

  • Download the latest version of myTracker.aar.

  • Copy myTracker.jar to libs directory of your project.

  • Add myTracker.jar to your project as a library.

  • Add next dependencies to your application build.gradle file:

    dependencies {
        ...
        implementation 'com.android.installreferrer:installreferrer:1.0'
        implementation 'com.google.android.gms:play-services-ads-identifier:15.0.1'
    }
  • If using Proguard make sure to add an exception:

    -keep class com.my.tracker.** { *; }
    -dontwarn com.my.tracker.**
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient {
        com.google.android.gms.ads.identifier.AdvertisingIdClient$Info getAdvertisingIdInfo(android.content.Context);
    }
    -keep class com.google.android.gms.ads.identifier.AdvertisingIdClient$Info {
        java.lang.String getId();
        boolean isLimitAdTrackingEnabled();
    }
    -keep class com.android.installreferrer.** { *; }
    -keep class com.android.vending.billing.** { *; }
    -keep class com.android.billingclient.api.** { *; }

Required permissions

Add required permissions to your app’s AndroidManifest.xml at "manifest" section:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Receiving Android referrer

If myTracker is the only SDK used to receive and track android referrer, you should add declaration of CampaignReceiver receiver and CampaignService to your manifest file.

<application>
<receiver android:name="com.my.tracker.campaign.CampaignReceiver"
          android:permission="android.permission.INSTALL_PACKAGES"
          android:exported="true">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER"/>
    </intent-filter>
</receiver>
<service android:name="com.my.tracker.campaign.CampaignService"/>
</application>

However, if several SDK needs to get android referrer, only fist declared receiver will receive it, since applications could not has several receivers on a single intent-filter. To handle this issue, myTracker SDK defines MultipleInstallReceiver class, which will send android referrer to all receivers defined in manifest file. To use this feature, just add myTracker receiver on top of other receivers in manifest file. Also you must add CampaignService definition.

<application>
    <receiver android:name="com.my.tracker.campaign.MultipleInstallReceiver"
              android:permission="android.permission.INSTALL_PACKAGES"
              android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER"/>
        </intent-filter>
    </receiver>
    ...
    <receiver android:name="some other receiver" android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER"/>
        </intent-filter>
    </receiver>
    ...
    <service android:name="com.my.tracker.campaign.CampaignService"/>
</application>

Initialization

For correct myTracker SDK operation, create an instance, set it up and initialize inside of onCreate method of an Application class of your app. To create an instance you have to enter your SDK_KEY. After creating the instance, initialization needs to be completed. Between creating and initializing the instance, you may set different settings for the tracker.

public class YourApplicationClass extends Application
{
    @Override
    public void onCreate()
    {
        super.onCreate();

        // creating an instance
        MyTracker.createTracker(SDK_KEY, this);

        // set up with params if needed
        MyTrackerParams trackerParams = MyTracker.getTrackerParams();
        // …
        // Setting up params of trackerParams
        // …
        // Initialize instance
        MyTracker.initTracker();
    }
}

If you can't initialize myTracker inside Application class, you could do that in the first starting activity of your application. However, in this case you must call trackLaunchManually method of myTracker after initialization.

public class YourActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Create myTracker class instance
        MyTracker.createTracker(SDK_KEY, getApplication());

        // Setup myTracker params (optional)
        MyTrackerParams trackerParams = MyTracker.getTrackerParams();
        // ...
        // Setting up params via trackerParams instance
        // ...

        // Init myTracker
        MyTracker.initTracker();

        //Enable activity tracking
        MyTracker.trackLaunchManually(this);
    }
}

API

Tracker parameters

All parameters can be set up in MyTrackerParams class instance available through MyTracker.getTrackerParams() method. Currently available:

App launch tracking. true by default.

void setTrackingLaunchEnabled(boolean trackingLaunchEnabled)

An interval (in seconds) during which a new launch is not tracked and a session is not interrupted while app is in background. 30 seconds by default. Possible value range: 30-7200 seconds.

void setLaunchTimeout(int seconds)

An interval (in seconds) during which events will be accumulated locally on the device before sending to the server. Default value is 900 seconds, allowed values are: 1-86400 seconds (1 day).

void setBufferingPeriod(int seconds)

An interval (in seconds) starting from application install/update during which any new event will be send to the server immediately, without local buffering. Default value is set to 0 (immediate sending is disabled), allowed values are 0-432000 seconds (5 days).

void setForcingPeriod(int seconds)

If inApp purchase events should be tracked automatically. true by default.

void setAutotrackingPurchaseEnabled(boolean autotrackingPurchaseEnabled)

Geolocation tracking. true by default.

void setTrackingLocationEnabled(boolean trackingLocationEnabled)

Region, where the data collection server is located. Choose a region based, for example, on current legislation. Available values:

  • Region.RU — server on the territory of Russian Federation

  • Region.EU — server on the territory of Europe

void setRegion(int region)

Enable/disable debug mode

Enabling and disabling debug mode can be done via MyTracker class static methods. false by default.

@AnyThread
void setDebugMode(boolean debugMode)

Track users

Set the customUserId parameter to track user stats, not only device. It's a unique user identifier in the project, that you specify at the time of registration. The identifier should remain unchanged even when user switch devices. The parameter allows you to estimate the size and activity of user base, regardless of the number of user devices. Also you can keep your customer data consistent if a user changes a device.

It's essential to set the parameter before tracking events to pass user identifier with every event.

public void setUserInfo()
{
    MyTrackerParams trackerParams = MyTracker.getTrackerParams();

    // Set user id
    trackerParams.setCustomUserId("user_id");

}

If customUserId was set to the application with an existing registered users, myTracker can't calculate exact Lifetime metrics without registration time. For pre-registered users, Lifetime statistic will be count on the date of the first tracked event with customUserId.

To turn off user tracking, pass an empty value in the customUserId parameter.

Track events

Events can be sent via MyTracker class static methods. Before you call methods, set the customUserId parameter to pass user identifier with every tracked event.

The following methods for event tracking are available:

Registration event. Returns false, if it’s not added to queue for sending. You should call the method right after user registered in the app and got a unique identifier. It's essential to set the customUserId parameter before you call TrackRegistrationEvent. This parameter allows you to pass user identifier with tracked event and get reliable user stats.

@AnyThread
boolean trackRegistrationEvent()

Login event. Returns false, if it’s not added to queue for sending.

You should call the method right after user successfully authorized in the app and got a unique identifier. It's essential to set the customUserId parameter before you call TrackLoginEvent. This parameter allows you to pass user identifier with tracked event and get reliable user stats.

@AnyThread
boolean trackLoginEvent()

Invite event. Any optional parameters can be passed with event as "key-value" by optional parameter eventParams. Max key or value length — 64 chars. Returns false, if it’s not added to queue for sending.

@AnyThread
boolean trackInviteEvent()
@AnyThread
boolean trackInviteEvent(Map<String, String> eventParams)

Level up event. Level parameter is optional. Any optional parameters can be passed with event as "key-value" by optional parameter eventParams. Max key or value length — 64 chars. Returns false, if it’s not added to queue for sending.

@AnyThread
boolean trackLevelEvent()
@AnyThread
boolean trackLevelEvent(Map<String, String> eventParams)
@AnyThread
boolean trackLevelEvent(int level, Map<String, String> eventParams)

Any user defined event with a custom name. Any optional parameters can be passed with event as "key-value" by optional parameter eventParams. Max name, key or value length — 64 chars. Returns false, if it’s not added to queue for sending.

@AnyThread
boolean trackEvent(String name)
@AnyThread
boolean trackEvent(String name, Map<String, String> eventParams)

Example:

Map<String, String> eventParams = new HashMap<>();
eventParams.put("someParamKey1", "someParamValue1");
eventParams.put("someParamKey2", "someParamValue2");
MyTracker.trackEvent("eventName", eventParams);

Force sending events from local buffer to server and reset buffering timers.

The SDK, which reduces channel load and lowers impact on app performance, collects all data on the device before sending it off to the server and regularly does so in a compressed format. By default, data is sent every 15 minutes. The interval can be changed to anywhere from 1 second to 1 day through the bufferingPeriod property. If the user has quit the app, the events will be sent during next launch. It's extremely important to analyse certain events as soon as possible, especially in the first sessions since installing the app. The flush() method will help.

@AnyThread
boolean flush()

Track in app purchases

Play Billing Library

If you use the Play Billing Library, for automatic purchase events tracking you must call the corresponding myTracker method from onPurchasesUpdated method of BillingClient listener.

private BillingClient client;
...
client = BillingClient.newBuilder(context)
                 .setListener(new PurchasesUpdatedListener()
                 {
                    @Override
                    public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases)
                    {
                        MyTracker.onPurchasesUpdated(responseCode, (List) purchases);


                        // Your code for in app purchase handling
                        // ...
                    }
                 })
                 .build();
...

In-app Billing API

If you use you own In-App Billing API implementation, for automatic purchase events tracking you must call the corresponding myTracker method from onActivityResult method of activity that started the purchase process.

public static final int PURCHASE_REQUEST_CODE = 1001;
...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
   super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == PURCHASE_REQUEST_CODE)
   {
        MyTracker.onActivityResult(resultCode, data);
        // Your code for in app purchase handling
        // ...
   }
}
...

Manual in app purchases tracking

If you would like to track in app purchase events manually, you shoud disable auto tracking by setting autotrackingPurchaseEnabled = false and use myTracker methods:

@AnyThread
boolean trackPurchaseEvent(@NonNull JSONObject skuDetails,
       @NonNull JSONObject purchaseData,
       @NonNull String dataSignature)
@AnyThread
boolean trackPurchaseEvent(@NonNull JSONObject skuDetails,
       @NonNull JSONObject purchaseData,
       @NonNull String dataSignature,
       @Nullable Map<String, String> eventParams)

If auto tracking is enabled, this methods calls will be ignored. Required parameters:

  • skuDetails — return value of getSkuDetails() method call according to documentation
  • purchaseData — JSON object in INAPP_PURCHASE_DATA field of getBuyIntent() method return value, according to documentation
  • dataSignature — string from INAPP_DATA_SIGNATURE field of getBuyIntent() method return value

Since data returned by methods getSkuDetails() and getBuyIntent() comes as Bundle with String type fields in it, transformation to JSONObject before send is required.

Any optional parameters can be passed with event as "key-value" by optional parameter eventParams. Max key or value length — 64 chars.

public static final int PURCHASE_REQUEST_CODE = 1001;
...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
   super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == PURCHASE_REQUEST_CODE && resultCode == RESULT_OK)
   {
      try
      {
         final String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
         final String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");

         final JSONObject purchaseDataJson = new JSONObject(purchaseData);

         // Receive skuDetails response
         final JSONObject skuDetailsJson = obtainSkuDetailJson(purchaseData);

         MyTracker.trackPurchaseEvent(skuDetailsJson, purchaseDataJson, dataSignature);


        // Your code for in app purchase handling
        // ...
      }
      catch (Exception ignored)
      {
      }
   }
}
...

Deeplinks

Deep links allow to pass additional parameters to application on application launch, for example, to open specific application screen.

Deferred deep links extend regular deep links and allow to pass additional parameters to recently installed application on the first application launch. Similar to regular deep links, this parameters could be used to open specific application screen or start an specific activity.

Detailed information on different deep link types support in myTracker could be found in our documentation Deep link settings

To allow myTracker to handle regular deep links, in each application activity which support deep links in onCreate and onNewIntent methods you must call handleDeeplink method of myTracker.

public class SomeActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate();
        // ...
        String deeplink = MyTracker.handleDeeplink(getIntent());
        if(deeplink != null)
        {
            // Handle deep link
        }
    }


    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        // ...
        String deeplink = MyTracker.handleDeeplink(intent);
        if(deeplink != null)
        {
            // Handle deep link
        }
    }
}

Deferred deep links

To support deferred deep links in your app you need to add a listener which implement the MyTracker.AttributionListener interface. The listener would be called out just once, at first launch of the app if a deferred deep link is found.

As a parameter to the onReceiveAttribution method, the MyTrackerAttribution attribution object containing the deep link property would be passed. Check that the property value belongs to your app otherwise a third-party app might open when using Intent transition.

public class YourApplicationClass extends Application
{
    @Override
    public void onCreate()
    {
        super.onCreate();

        // Create tracker instance
        MyTracker.createTracker(SDK_KEY, this);

        // Set up parameters if needed
        MyTrackerParams trackerParams = MyTracker.getTrackerParams();
        // ...
        // Setting up tracker parameters trackerParams
        // ...


        // Set listener to receive the deferred deep link
        MyTracker.setAttributionListener(new MyTracker.AttributionListener()
        {

            @Override
            public void onReceiveAttribution(MyTrackerAttribution attribution)
            {
                String deeplink = attribution.deeplink;
                // Processing the deferred deep link
                // ...
            }
        });

        // Initialize myTracker instance
        MyTracker.initTracker();
    }
}

You may set up a Handler for listener method execution when setting the listener with the setAttributionListener(AttributionListener attributionListener, Handler handler) method. If no Handler is set up when installing the listener then the onReceiveAttribution method would be called in the main application flow.