Android SDK
- Configuring Your Project
- Disabling Metrix in Some Build Variants (Optional)
- Additional Features
- Sessions
- Session Identifier
- Current Session Number
- Events
- Custom Events
- Specify the Default Attributes for a User
- Track Revenue
- Device Identifier
- Uninstall Tracking
- Get User Attribution Information
- Deep Linking
- Standard Deep Linking Scenario
- Deferred Deep Linking Scenario
- Pre-Installed Trackers
- Separating Organic Installations Based on Stores
- Implement Push Notification
- Configuring Your Webview
- Features
- Sessions
- Session Identifier
- Current Session Number
- Events
- Custom Events
- Specify the Default Attributes for a User
- Revenue
- Device Identifier
- Get User Attribution Information
- Deep Linking
- Deferred Deep Linking Scenario
You can find a sample application for implementing Metrix Android SDK here.
By following the few steps below, Metrix library will be ready to use in your application:
1. Inside the app-level build.gradle
file, make sure the compileSdkVersion
is set to at least 31.
android {
compileSdkVersion 32 // >= 31
// ...
}
2. Add mavenCentral
repository in your project-level build.gradle
. (In newer versions of Gradle
it's set in settings.gradle
file)
allprojects {
repositories {
// ...
mavenCentral()
}
}
3. Add Metrix dependency in your app-level build.gradle
file:(according to your needs add attribution or analytics or both sdk versions)
implementation 'ir.metrix.attribution:metrix:2.0.0'
implementation 'ir.metrix.analytics:metrix:2.0.0'
4. Add your Metrix application id as an application meta-data
inside AndroidManifest.xml
file:
<manifest>
...
<application>
...
<!-- Add the following lines and replace YOUR_APP_ID -->
<meta-data
android:name="ir.metrix.APPLICATION_ID"
android:value="YOUR_APP_ID" />
</application>
</manifest>
Replace YOUR_APP_ID
with your application id. You can find the id in your Metrix dashboard under application settings.
5. Add your Metrix api key as an application meta-data
inside AndroidManifest.xml
file:
<manifest>
...
<application>
...
<!-- Add the following lines and replace YOUR_API_KEY -->
<meta-data
android:name="ir.metrix.API_KEY"
android:value="YOUR_API_KEY" />
</application>
</manifest>
Replace YOUR_API_KEY
with your api key. You can find the key in your Metrix dashboard under application settings.
6. Metrix provides dedicated SDK signature for your application as an extra layer of security to prevent possible data frauds using SDK spoofing, that is necessary to implement.
To use SDK signature you should first enable the feature in your dashboard under application settings and create a signature for your application. For each created SDK signature, there is a secret string under the Encoded
column. You should put that string as an application meta-data
in the AndroidManifest.xml
file like the following:
<manifest>
...
<application>
...
<!-- Add the following lines and replace YOUR_SIGNATURE -->
<meta-data
android:name="ir.metrix.SIGNATURE"
android:value="YOUR_SIGNATURE" />
</application>
</manifest>
You can disable Metrix library when development or other build variants depending on your needs and your application's configuration. When disabled, Metrix will not gather any install, session or events info and the data will be ignored.
To disable Metrix, you need to add the following application meta-data
inside AndroidManifest.xml
file:
<manifest>
...
<application>
...
<!-- Add the following lines -->
<meta-data
android:name="metrix_developer_mode"
android:value="true" />
</application>
</manifest>
Using Android's manifestPlaceholders gradle config, you can disable Metrix for specific application's build variants inside app-level build.gradle
file.
In the following example, Metrix is disabled in development builds and enabled in release builds:
<manifest>
...
<application>
...
<meta-data
android:name="metrix_developer_mode"
android:value="${metrixDisabled}" />
</application>
</manifest>
android {
// ...
buildTypes {
debug {
//...
manifestPlaceholders = [metrixDisabled: "true"]
}
release {
//...
manifestPlaceholders = [metrixDisabled: "false"]
}
}
}
In Metrix, a session is a specific timeframe during which the user interacts with the application. These sessions and the data related to them are captured by the Metrix SDK and provided to you in your dashboard.
For each session, our SDK generates a unique identifier. You can obtain this identifier by introducing a listener using the following method:
MetrixAnalytics.setSessionIdListener(new SessionIdListener() {
@Override
public void onSessionIdChanged(String sessionId) {
// your logic
}
});
Whenever a new session is started, your listener will be called with the new session's identifier.
Using the following method, you can provide a listener for current session number:
MetrixAnalytics.setSessionNumberListener(new SessionNumberListener() {
@Override
public void onSessionNumberChanged(String sessionNumber) {
// your logic
}
});
Whenever a new session is started, your listener will be called with the new session's number.
Each interaction that the user has with your application can be introduced as an event in your dashboard and application in order for Metrix to collect and present its statistics.
There are two types of events in Metrix:
- Custom: Depending on your application logic and the interaction that the user has with your app, you can create and send custom events.
- Revenue: A special type of custom events you can specify for tracking your application revenue.
You can use Metrix to track any events in your application. Suppose you want to track every tap on a button. You would have to create a new event in the Events Management section of your dashboard and retrieve the generated slug
for the event. The slug is to be used in the application code to send the event to Metrix library. So In your button's onClick method you could then invoke the Metrix newEvent
method providing the event slug and optionally some attributes related to the event like the following:
// Send a simple event
MetrixAnalytics.newEvent("my_event_slug");
// Send an event with attributes
Map<String, String> attributes = new HashMap<>();
attributes.put("first_name", "Ali");
attributes.put("last_name", "Bagheri");
MetrixAnalytics.newEvent("purchase_event_slug", attributes);
The parameters for the newEvent
method are as follows:
- First parameter: The event slug which is a String you receive from the Metrix dashboard.
- Second parameter (optional): A
Map<String, String>
that specifies the attributes of an event.
Note: Each event can have up to total 50 attributes with each attribute having a limit of 512 bytes in key and 512 bytes in value.
Using the following method, you can add arbitrary attributes
to all events of the user:
Map<String, String> attributes = new HashMap<>();
attributes.put("manufacturer", "Nike");
MetrixAnalytics.User.setCustomAttribute(attributes);
Note: Each event can have up to total 50 attributes with each attribute having a limit of 512 bytes in key and 512 bytes in value.
and with the following methods, you can add specific attributes for user:
MetrixAnalytics.User.setUserCustomId("userId"); // call when user tries to login in your system and set userId value that user already knows in your system
MetrixAnalytics.User.deleteUserCustomId(); // call when your user goes to logout in your system
MetrixAnalytics.User.setFirstName("userFirstName");
MetrixAnalytics.User.setLastName("userLastName");
MetrixAnalytics.User.setPhoneNumber("phoneNumber");
MetrixAnalytics.User.setHashedPhoneNumber("hashedPhoneNumber");
MetrixAnalytics.User.setEmail("email");
MetrixAnalytics.User.setHashedEmail("hashedEmail");
MetrixAnalytics.User.setCountry("country");
MetrixAnalytics.User.setCity("city");
MetrixAnalytics.User.setRegion("region");
MetrixAnalytics.User.setLocality("locality");
MetrixAnalytics.User.setGender(gender);
MetrixAnalytics.User.setBirthday(birthday); // birthday value type should be 'Long'
MetrixAnalytics.User.setFcmToken("fcmToken");
MetrixAnalytics.User.setChannelEnabled(channel);
MetrixAnalytics.User.setChannelDisabled(channel);
If your users can generate revenue by tapping on advertisements or making in-app purchases, you can track those revenues with a special type of Metrix custom event. This is specially useful for tracking in-app purchases. Like any custom event, revenues must be defined in dashboard event management section to retrieve the slug. You can see an example below where a tap is worth 12,000 IRR:
MetrixAnalytics.newRevenue("my_event_slug", 12000, RevenueCurrency.IRR, "myOrderId");
- The first parameter is the slug you get from the dashboard.
- The second parameter is the amount of revenue.
- The third parameter is the currency of this event which can be
MetrixCurrency.IRR
(Default),MetrixCurrency.USD
, orMetrixCurrency.EUR
. - The fourth parameter is your order identifier (optional).
For each device with your app installed on, our service generates a unique identifier. You can obtain this identifier by introducing a listener using the following method:
MetrixAnalytics.setUserIdListener(new UserIdListener() {
@Override
public void onUserIdReceived(String metrixUserId) {
// your logic
}
});
or
MetrixAttribution.setUserIdListener(new UserIdListener() {
@Override
public void onUserIdReceived(String metrixUserId) {
// your logic
}
});
The listener will be called once the identifier is fetched by our SDK.
Metrix application uninstall tracking relies on silent push notifications to determine if your application is installed on a device.
You must configure your application for push notifications through Firebase Cloud Messaging (FCM).
Developer instructions for configuring your app for uninstall tracking can be found below.
- Add Firebase push credentials to Metrix panel.
In the Metrix dashboard, navigate to your application and select your application settings. Select Push configuration. In this page, Push configuration is divided into two sections. Legacy mode and New mode. we recommend to use both modes. enter credentials and click save.
New mode
You can get Service Account Date from project settings in Service Accounts by clicking generate new private key.
Legacy mode
You can get server key
and sender id
from project settings in Cloud Messaging tab of your Firebase console.
- Enable uninstall tracking
After providing credentials in application push configuration section, enable uninstall tracking by switching the following toggle in the same section.
- Send FCM push token in application
After implementing FCM push notification service in your application, send FCM push token to Metrix SDK by invoking the following method whenever a new token is received:
MetrixAttribution.setPushToken("pushToken");
You can obtain the information about the user's attribution by introducing a listener using the following method:
MetrixAttribution.setOnAttributionChangedListener(new OnAttributionChangeListener() {
@Override
public void onAttributionChanged(AttributionData attributionData) {
//TODO
}
});
The listener will be called once the attribution data is fetched by the SDK provided with an instance of AttributionData
class.
Here is a quick summary of AttributionData
class properties:
attributionData.getAcquisitionAd() // The creative/ad grouping level of the current attribution.
attributionData.getAcquisitionAdSet() // The adGroup/adSet grouping level of the current attribution.
attributionData.getAcquisitionCampaign() // The campaign grouping level of the current attribution.
attributionData.getAcquisitionSource() // The network/source grouping level of the current attribution.
attributionData.getAcquisitionSubId() // The subId level of the current attribution.
attributionData.getAttributionStatus() // An Enum Specifying the status of the user in the campaign.
AttributionStatus
Enum has one of the values below:
ATTRIBUTED
NOT_ATTRIBUTED_YET
ATTRIBUTION_NOT_NEEDED
UNKNOWN
If you are using Metrix tracker URLs with deep linking enabled, it is possible to receive information about the deep link URL and its content. Users may interact with the URL regardless of whether they have your app installed on their device (standard deep linking scenario) or not (deferred deep linking scenario). In the standard deep linking scenario, the Android platform natively offers the possibility for you to receive deep link content information. The Android platform does not automatically support deferred deep linking scenario; in this case, the Metrix SDK offers the mechanism you need to get the information about the deep link content.
If a user has your application installed and you want it to launch to a specific content after they engage with an Metrix tracker URL containing a deep link
, enable deep linking in your app. This is done by choosing a desired unique scheme name. You'll assign it to the activity you want to launch once your app opens following a user selecting the tracker URL in theAndroidManifest.xml
file. Add the intent-filter
section to your desired activity definition in the manifest file and assign an android:scheme
property value with the desired scheme name:
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="metrixExample" />
</intent-filter>
</activity>
Deep link content information within your desired activity is delivered via the Intent
object, via either the activity's onCreate
or onNewIntent
methods. Once you've launched your application and have triggered one of these methods, you will be able to receive the actual deep link passed in the deep link parameter when defining the tracker. You can then use this information to conduct some additional logic in your app.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Uri data = intent.getData();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Uri data = intent.getData();
}
Deferred deep linking scenario occurs when a user clicks on a Metrix tracker URL containing a deep link, but does not have the app installed on the device at click time. When the user clicks the URL, he/she will be redirected to the Google Play Store to download and install your app. After opening it for the first time, the deep link content will be delivered to your app.
If you wish to control if the Metrix SDK will open the deferred deep link, you can do so by providing the following listener:
MetrixAttribution.setOnDeeplinkResponseListener(new OnDeeplinkResponseListener() {
@Override
public boolean launchReceivedDeeplink(Uri deeplink) {
// ...
if (shouldMetrixSdkLaunchTheDeeplink(deeplink)) {
return true;
} else {
return false;
}
}
});
After the Metrix SDK receives the deep link information from our server, the SDK will deliver you its content via the listener and expect a boolean
return value from you. This return value represents your decision on whether or not the Metrix SDK should launch the activity to which you have assigned the scheme name from the deep link (like in the standard deep linking scenario).
If you return true
, we will launch it, triggering the scenario described in the Standard deep linking scenario chapter. If you do not want the SDK to launch the activity, return false
from the listener, and (based on the deep link content) decide on your own what to do next in your app.
Note: Deferred deep linking scenario is only available for users installing the application from Google Play Store.
If you want to use the Metrix SDK to recognize users whose installation has not been triggered by an ad click, set the default tracker in your application using the following application meta-data
in AndroidManifest.xml
file. Replace TOKEN
with the tracker token you created in the dashboard.
<manifest>
...
<application>
...
<!-- Add the following line and replace "TOKEN" with your tracker token -->
<meta-data
android:name="metrix_trackerToken"
android:value="TOKEN" />
</application>
</manifest>
This feature is introduced to be used when you intend to track installations that has not been triggered by an ad click. In other words, if you want to publish an APK file of your application on some platform other than application stores to be downloaded and opened directly by users, to attribute these users to a tracker you should specify the tracker token in your application using this feature; otherwise, these installations will all be considered organic.
Note: You should never publish your application containing a pre-installed tracker in an application store; otherwise, all the installations from that store including the organic ones will be considered sourced from the specified tracker.
If you wish to publish your application in different application stores and intend to split the organic users by the store from which they have downloaded the application, you can have a separate build for each store and put the following application meta-data
in AndroidManifest.xml
file replacing YOUR_STORE_NAME
with corresponding store name in each build:
<manifest>
...
<application>
...
<!-- Add these lines and replace "STORE_NAME" -->
<meta-data
android:name="metrix_storeName"
android:value="YOUR_STORE_NAME" />
</application>
</manifest>
1. Add Metrix dependency in your app-level build.gradle
file:
implementation 'ir.metrix.notification:metrix:2.0.0'
2. Add metrix notification receive method in your Custom FirebaseMessagingService
class:
class CustomFirebaseMessagingService: FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
if (MetrixNotification.onMessageReceived(message)) return
// here you can process your own fcm messages
}
}
Note: For now we only send notification to your known user, so user should have customUserId
to be able to receive push
3. Set customUserId
on user login and delete it when user logged out:
MetrixAnalytics.User.setUserCustomId("yourId")
MetrixAnalytics.User.deleteUserCustomId()
Note: If you wanna add firebase dependency, exclude firebase-iid
and firebase-messaging
After receiving a reference to your Webview
:
- invoke the following method to enable
javascript
in your webview:
yourWebView.getSettings().setJavaScriptEnabled(true);
- invoke the following method to enable Metrix bridge from native library to your webview:
MetrixAnalyticsBridge.registerAndGetInstance(yourWebview);
MetrixAttributionBridge.registerAndGetInstance(yourWebview);
Note: If you need to change your webview object at some point, use the following method:
MetrixAnalyticsBridge.setWebView(newWebview);
MetrixAttributionBridge.setWebView(newWebview);
Note: To disable the Metrix bridge use the following method:
MetrixAnalyticsBridge.unregister();
MetrixAttributionBridge.unregister();
Following the steps above, your Activity
class should be similar to the code below:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
MetrixAnalyticsBridge.registerAndGetInstance(webview);
MetrixAttributionBridge.registerAndGetInstance(webview);
try {
webView.loadUrl("your webview content");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
MetrixAnalyticsBridge.unregister();
MetrixAttributionBridge.unregister();
super.onDestroy();
}
}
Metrix SDK is now enabled in your application and you can use the metrix_analytics.js
or metrix_attribution.js
script which is automatically added to your project as the interface.
Simply import the metrix_analytics.js
or metrix_attribution.js
file as a script in your HTML
file and use the provided methods of MetrixAnalytics
or MetrixAttribution
class.
<script type="text/javascript" src="metrix_analytics.js"></script>
<script type="text/javascript" src="metrix_attribution.js"></script>
In Metrix, a session is a specific timeframe during which the user interacts with the application. These sessions and the data related to them are captured by the Metrix SDK and provided to you in your dashboard.
For each session, our SDK generates a unique identifier. You can obtain this identifier String by calling the following method:
MetrixAnalytics.setSessionIdListener(metrixSessionId => {
//TODO
});
Using the following method, you can obtain the current session number:
MetrixAnalytics.setSessionNumberListener(metrixSessionNumber => {
//TODO
});
Each interaction that the user has with your application can be introduced as an event in your dashboard and application in order for Metrix to collect and present its statistics.
There are two types of events in Metrix:
- Custom: Depending on your application logic and the interaction that the user has with your app, you can create and send custom events.
- Revenue: A special type of custom events you can specify for tracking your application revenue.
You can use Metrix to track any events in your application. Suppose you want to track every tap on a button. You would have to create a new event in the Events Management section of your dashboard and retrieve the generated slug
for the event. The slug is to be used in the application code to send the event to Metrix library. So In your button's onClick method you could then invoke the Metrix newEvent
method providing the event slug and optionally some attributes related to the event like the following:
// Send a simple event
MetrixAnalytics.newEvent("my_event_slug");
// Send an event with attributes
var attributes = {};
attributes["first_name"] = "Ali";
attributes["last_name"] = "Bagheri";
MetrixAnalytics.newEvent("my_event_slug", attributes);
The parameters for the newEvent
method are as follows:
- First parameter: The event slug which is a String you receive from the Metrix dashboard.
- Second parameter (optional): A
Map<String, String>
that specifies the attributes of an event.
Note: Each event can have up to total 50 attributes with each attribute having a limit of 512 bytes in key and 512 bytes in value.
Using the following method, you can add arbitrary attributes
to all events of the user:
var attributes = {};
attributes["manufacturer"] = "Nike";
MetrixAnalytics.setUserAttributes(attributes);
and with the following methods, you can add specific attributes:
MetrixAnalytics.setUserCustomId("yourCustomUserId"); // call when user tries to login in your system and set userId value that user already knows in your system
MetrixAnalytics.deleteUserCustomId(); // call when your user goes to logout in your system
MetrixAnalytics.setUserFirstName("userFirstName");
MetrixAnalytics.setUserLastName("userLastName");
MetrixAnalytics.setUserPhoneNumber("phoneNumber");
MetrixAnalytics.setUserHashedPhoneNumber("hashedPhoneNumber");
MetrixAnalytics.setUserEmail("email");
MetrixAnalytics.setUserHashedEmail("hashedEmail");
MetrixAnalytics.setUserCountry("country");
MetrixAnalytics.setUserCity("city");
MetrixAnalytics.setUserRegion("region");
MetrixAnalytics.setUserLocality("locality");
MetrixAnalytics.setUserGender(gender); // gender value could be "MALE" , "FEMALE" or "OTHER"
MetrixAnalytics.setUserBirthday(birthday); // birthday value type should be 'Long' timestamp
MetrixAnalytics.setUserFcmToken("fcmToken");
MetrixAnalytics.userChannelEnabled(channel); // channel value could be "SMS", "PUSH" or "EMAIL"
MetrixAnalytics.userChannelDisabled(channel); // channel value could be "SMS", "PUSH" or "EMAIL"
Note: Each event can have up to total 50 attributes with each attribute having a limit of 512 bytes in key and 512 bytes in value.
If your users can generate revenue by tapping on advertisements or making in-app purchases, you can track those revenues with a special type of Metrix custom event. This is specially useful for tracking in-app purchases. Like any custom event, revenues must be defined in dashboard event management section to retrieve the slug. You can see an example below where a tap is worth 12,000 IRR:
MetrixAnalytics.newRevenue("my_event_slug", 12000, "IRR");
- The first parameter is the slug you get from the dashboard.
- The second parameter is the amount of revenue.
- The third parameter is the currency of this event which can be
IRR
(Default),USD
, orEUR
. - The fourth parameter is your order identifier (optional).
For each device with your app installed on, our service generates a unique identifier. You can obtain this identifier by introducing a listener using the following method:
MetrixAttribution.setUserIdListener(metrixUserId => {
//TODO
});
The listener will be called once the identifier is fetched by our SDK.
You can obtain the information about the user's attribution by introducing a listener using the following method:
MetrixAttribution.setOnAttributionChangedListener(attributionData => {
//TODO
});
The listener will be called once the attribution data is fetched by the SDK provided with an instance of AttributionData
class.
Here is a quick summary of AttributionData
class properties:
attributionData.acquisitionAd // The creative/ad grouping level of the current attribution.
attributionData.acquisitionAdSet // The adGroup/adSet grouping level of the current attribution.
attributionData.acquisitionCampaign // The campaign grouping level of the current attribution.
attributionData.acquisitionSource // The network/source grouping level of the current attribution.
attributionData.acquisitionSubId // The subId level of the current attribution.
attributionData.attributionStatus // An Enum Specifying the status of the user in the campaign.
AttributionStatus
Enum has one of the values below:
ATTRIBUTED
NOT_ATTRIBUTED_YET
ATTRIBUTION_NOT_NEEDED
UNKNOWN
If you are using Metrix tracker URLs with deep linking enabled, it is possible to receive information about the deep link URL and its content. Users may interact with the URL regardless of whether they have your app installed on their device (standard deep linking scenario) or not (deferred deep linking scenario). In the standard deep linking scenario, the Android platform natively offers the possibility for you to receive deep link content information. The Android platform does not automatically support deferred deep linking scenario; in this case, the Metrix SDK offers the mechanism you need to get the information about the deep link content.
Deferred deep linking scenario occurs when a user clicks on a Metrix tracker URL containing a deep link, but does not have the app installed on the device at click time. When the user clicks the URL, he/she will be redirected to the Google Play Store to download and install your app. After opening it for the first time, the deep link content will be delivered to your app.
If you wish to control if the Metrix SDK will open the deferred deep link, you can do so by providing the following listener:
MetrixAttribution.shouldLaunchDeeplink = true;
MetrixAttribution.setOnDeeplinkResponseListener(deeplink => {
//TODO
});
After the Metrix SDK receives the deep link information from our server, the SDK will deliver you its content via the listener. Also the SDK expects the shouldLaunchDeeplink
boolean
value from you. This value represents your decision on whether or not the Metrix SDK should launch the activity to which you have assigned the scheme name from the deep link (like in the standard deep linking scenario).
If you set the value to true
, we will launch it, triggering the scenario described in the Standard deep linking scenario chapter. If you do not want the SDK to launch the activity, set the boolean value to false
, and (based on the deep link content) decide on your own what to do next in your app.
Note: Deferred deep linking scenario is only available for users installing the application from Google Play Store.