Usage examples
- Library initialization with the extended configuration
- Sending statistics to an additional API key
- Manually monitoring app crashes
- Using the library to send device location
- Setting location manually
- Sending a custom event
- Sending a custom event with nested parameters
- Sending a custom error message
- Sending events from the buffer
- Monitoring the app lifecycle manually
- Sending ProfileId
- Sending profile attributes
- Sending E-commerce events
- Sending in-app purchases
- Sending Ad Revenue data on Flutter
- Tracking app opens using deeplinks
- Getting AppMetrica SDK IDs
Library initialization with the extended configuration
To initialize the library with an extended startup configuration, pass an AppMetricaConfig
instance with appropriate settings and activate the library using the AppMetrica.activate(AppMetricaConfig config)
method. Using an extended configuration, you can enable or disable logging, set session timeout, pass parameters for tracking pre-installed apps, and so on.
Extended configuration settings take effect immediately upon library initialization.
AppMetrica.activate(
AppMetricaConfig(API_KEY, logs: true
// ...
));
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 an extended configuration, create an instance of the AppMetricaReporterConfig
class and specify the necessary configurations. Then, activate the reporter using the AppMetrica.activateReporter(AppMetricaReporterConfig reporterConfig)
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.
Alert
The reporter with an 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 a ANOTHER_API_KEY that is different from the app's API_KEY.
AppMetricaReporterConfig reporterConfig = AppMetricaReporterConfig("ANOTHER_API_KEY",
// Setting up the configuration. For example, to enable logging.
logs: true);
// Initializing a reporter.
AppMetrica.activateReporter(reporterConfig);
Step 2. Configure sending data using a reporter
To send data using a reporter, first get the object that implements the AppMetricaReporter
abstract class by calling the AppMetrica.getReporter(String apiKey)
method. Then, use the interface methods for sending reports. If the reporter was not initialized with an extended configuration, calling this method will initialize the reporter for the specified API key.
Example of sending an event:
AppMetrica.getReporter("ANOTHER_API_KEY").reportEvent("Updates installed");
For correct tracking, manually configure the reporters to send events about the start and the pause of the session for each reporter. For this, use the resumeSession()
and pauseSession()
methods:
AppMetricaReporter reporter = AppMetrica.getReporter("ANOTHER_API_KEY");
reporter.resumeSession();
reporter.reportEvent("Updates installed");
reporter.pauseSession();
Manually monitoring app crashes
Reports on app crashes are sent by default. To prevent event duplication when sending crashes manually, disable the automatic monitoring of app crashes.
To send crash data manually, use the AppMetrica.reportUnhandledException(AppMetricaErrorDescription errorDescription)
method.
Using the library to send device location
Sending device location is disabled by default for Android. To enable sending it, initialize the library with the configuration where sending device location data is enabled. To do this, set the locationTracking
property to true
when creating an extended library configuration:
AppMetrica.activate(AppMetricaConfig(API_KEY,
locationTracking: true));
To enable sending at app runtime, use the AppMetrica.setLocationTracking(bool enabled)
method:
AppMetrica.setLocationTracking(true);
For more precise locations, add one of the following permissions to the AndroidManifest.xml file:
android.permission.ACCESS_COARSE_LOCATION
— For approximate determination.android.permission.ACCESS_FINE_LOCATION
— For accurate determination.
Setting location manually
Before sending custom information about the device location, make sure that report sending is enabled.
The library determines the device location on its own. To send your own data about the device location, pass AppMetricaLocation
to the AppMetrica.setLocation(AppMetricaLocation? location)
method:
// Determining the location.
AppMetricaLocation location = AppMetricaLocation(latitude, longitude);
// Setting up custom device location data.
AppMetrica.setLocation(location);
To send custom device location using an extended configuration, pass the AppMetricaLocation
instance to the location
property when creating an extended library configuration:
AppMetricaLocation location = AppMetricaLocation(latitude, longitude);
AppMetrica.activate(AppMetricaConfig(API_KEY,
location: location));
Sending a custom event
To send a custom event without nested parameters, pass a short name or description of the event to the AppMetrica.reportEvent(String eventName)
method:
AppMetrica.reportEvent("eventName");
Sending a custom event with nested parameters
To send parameters in JSON format:
String jsonAttributes = '{"item":"book","price":9.99}';
AppMetrica.reportEventWithJson("Purchase", jsonAttributes);
To send parameters as a Map object:
Map<String, dynamic> attributesMap = {"item": "book", "price": 9.99};
AppMetrica.reportEventWithMap("Purchase", attributesMap);
Sending a custom error message
To send a custom error message, use the following method:
AppMetrica.reportError(
message: "Error occurred",
errorDescription: AppMetricaErrorDescription(StackTrace.current),
);
To send an error message with a group ID:
AppMetrica.reportErrorWithGroup(
"IDENTIFIER",
message: "MESSAGE",
errorDescription: AppMetricaErrorDescription(StackTrace.current),
);
Sending events from the buffer
AppMetrica SDK does not send an event immediately after it occurred. The library stores event data in the buffer. The sendEventsBuffer
method sends data from the buffer and flushes it. Use the method to force sending stored events after passing important checkpoints of user scenarios.
AppMetrica.sendEventsBuffer();
Monitoring the app lifecycle manually
To monitor the app lifecycle, use the following methods:
-
Pause session:
AppMetrica.pauseSession();
-
Resume session or start a new one:
AppMetrica.resumeSession();
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 technical profile is created with the ID appmetrica_device_id
.
You can update ProfileId
at any time by calling setUserProfileID
:
AppMetrica.setUserProfileID("id");
Sending profile attributes
To send profile attributes, pass an instance of the UserProfile
class to the AppMetrica.reportUserProfile(UserProfile)
method.
UserProfile userProfile = UserProfile([
// Updating predefined attributes.
NameAttribute.withValue("John"),
GenderAttribute.withValue(Gender.MALE),
BirthDateAttribute.withAge(24),
NotificationEnabledAttribute.withValue(false),
// Updating custom attributes.
StringAttribute.withValue("string_attribute", "string"),
NumberAttribute.withValue("number_attribute", 55),
CounterAttribute.withDelta("counter_attribute", 1)
]);
// Setting the ProfileID using the method of the YandexMetrica class.
AppMetrica.setUserProfileID("id");
// Sending the UserProfile instance.
AppMetrica.reportUserProfile(userProfile);
Sending E-commerce events
AppMetrica doesn't let you segment E-commerce events into test and non-test events. If you use the main API key for debugging purchases, the test events are included in general statistics. Therefore, to debug E-commerce event sending, use a reporter to send statistics to the additional API key.
Step 1. Create a test app in AppMetrica
Specify the app parameters: link in the app store (if the app isn't published yet, leave the field empty), name, category, and time zone for generating reports.
To add another app, click Add app in the drop-down list in AppMetrica.
Step 2. 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 ECommerce class method.
The examples below show how to send specific types of events.
Opening a page
Map<String, String> payload = {
"configuration": "landscape",
"full_screen": "true",
};
// Creating a screen object.
ECommerceScreen screen = ECommerceScreen(
name: "ProductCardActivity", // Optional.
searchQuery: "danissimo maple syrup", // Optional.
payload: payload, // Optional.
categoriesPath: ["Promos", "Hot deal"] // Optional.
);
ECommerceEvent showScreenEvent = ECommerce.showScreenEvent(screen);
// Sending an e-commerce event.
AppMetrica.getReporter("Testing API key").reportECommerce(showScreenEvent);
Viewing a product card
Map<String, String> payload = {
"configuration": "landscape",
"full_screen": "true"
};
// Creating a screen object.
ECommerceScreen screen = ECommerceScreen(
name: "ProductCardActivity", // Optional.
searchQuery: "danissimo maple syrup", // Optional.
payload: payload, // Optional.
categoriesPath: ["Promos", "Hot deal"] // Optional.
);
ECommerceAmount amount =
ECommerceAmount(amount: Decimal.parse('4.53'), currency: "USD");
// Creating an actualPrice object.
ECommercePrice actualPrice =
ECommercePrice(fiat: amount, internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30_570_000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating an originalPrice object.
ECommercePrice originalPrice = ECommercePrice(
fiat: ECommerceAmount(amount: Decimal.parse('5.78'), currency: "USD"),
internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30570000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating a product object.
ECommerceProduct product = ECommerceProduct(
sku: "779213",
name: "Danissimo curd product 5.9%, 130 g", // Optional.
actualPrice: actualPrice, // Optional.
originalPrice: originalPrice, // Optional.
promocodes: ["BT79IYX", "UT5412EP"], // Optional.
payload: payload, // Optional.
categoriesPath: [
"Groceries",
"Dairy",
"Yogurts"
] // Optional.
);
ECommerceEvent showProductCardEvent =
ECommerce.showProductCardEvent(product, screen);
// Sending an e-commerce event.
AppMetrica.getReporter("Testing API key")
.reportECommerce(showProductCardEvent);
Viewing a product page
Map<String, String> payload = {
"configuration": "landscape",
"full_screen": "true"
};
// Creating a screen object.
ECommerceScreen screen = ECommerceScreen(
name: "ProductCardActivity", // Optional.
searchQuery: "danissimo maple syrup", // Optional.
payload: payload, // Optional.
categoriesPath: ["Promos", "Hot deal"] // Optional.
);
ECommerceAmount amount =
ECommerceAmount(amount: Decimal.parse('4.53'), currency: "USD");
// Creating an actualPrice object.
ECommercePrice actualPrice =
ECommercePrice(fiat: amount, internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30_570_000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating an originalPrice object.
ECommercePrice originalPrice = ECommercePrice(
fiat: ECommerceAmount(amount: Decimal.parse('5.78'), currency: "USD"),
internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30570000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating a product object.
ECommerceProduct product = ECommerceProduct(
sku: "779213",
name: "Danissimo curd product 5.9%, 130 g", // Optional.
actualPrice: actualPrice, // Optional.
originalPrice: originalPrice, // Optional.
promocodes: ["BT79IYX", "UT5412EP"], // Optional.
payload: payload, // Optional.
categoriesPath: [
"Groceries",
"Dairy",
"Yogurts"
] // Optional.
);
ECommerceEvent showProductDetailsEvent =
ECommerce.showProductDetailsEvent(product, screen);
// Sending an e-commerce event.
AppMetrica.getReporter("Testing API key")
.reportECommerce(showProductDetailsEvent);
Adding/removing an item to/from the cart
Map<String, String> payload = {
"configuration": "landscape",
"full_screen": "true"
};
// Creating a screen object.
ECommerceScreen screen = ECommerceScreen(
name: "ProductCardActivity", // Optional.
searchQuery: "danissimo maple syrup", // Optional.
payload: payload, // Optional.
categoriesPath: ["Promos", "Hot deal"] // Optional.
);
ECommerceAmount amount =
ECommerceAmount(amount: Decimal.parse('4.53'), currency: "USD");
// Creating an actualPrice object.
ECommercePrice actualPrice =
ECommercePrice(fiat: amount, internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30570000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating an originalPrice object.
ECommercePrice originalPrice = ECommercePrice(
fiat: ECommerceAmount(amount: Decimal.parse('5.78'), currency: "USD"),
internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30570000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating a product object.
ECommerceProduct product = ECommerceProduct(
sku: "779213",
name: "Danissimo curd product 5.9%, 130 g", // Optional.
actualPrice: actualPrice, // Optional.
originalPrice: originalPrice, // Optional.
promocodes: ["BT79IYX", "UT5412EP"], // Optional.
payload: payload, // Optional.
categoriesPath: [
"Groceries",
"Dairy",
"Yogurts"
] // Optional.
);
ECommerceReferrer referrer = ECommerceReferrer(
type: "button", // Optional.
identifier: "76890", // Optional.
screen: screen // Optional.
);
// Creating a cartItem object.
ECommerceCartItem addedItems1 = ECommerceCartItem(
product: product,
revenue: actualPrice,
quantity: Decimal.parse("1.0"),
referrer: referrer // Optional.
);
ECommerceEvent addCartItemEvent = ECommerce.addCartItemEvent(addedItems1);
// Sending an e-commerce event.
AppMetrica.getReporter("Testing API key").reportECommerce(addCartItemEvent);
ECommerceEvent removeCartItemEvent =
ECommerce.removeCartItemEvent(addedItems1);
// Sending an e-commerce event.
AppMetrica.getReporter("Testing API key")
.reportECommerce(removeCartItemEvent);
Starting and completing a purchase
Map<String, String> payload = {
"configuration": "landscape",
"full_screen": "true"
};
// Creating a screen object.
ECommerceScreen screen = ECommerceScreen(
name: "ProductCardActivity", // Optional.
searchQuery: "danissimo maple syrup", // Optional.
payload: payload, // Optional.
categoriesPath: ["Promos", "Hot deal"] // Optional.
);
ECommerceAmount amount =
ECommerceAmount(amount: Decimal.parse('4.53'), currency: "USD");
// Creating an actualPrice object.
ECommercePrice actualPrice =
ECommercePrice(fiat: amount, internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30570000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating an originalPrice object.
ECommercePrice originalPrice = ECommercePrice(
fiat: ECommerceAmount(amount: Decimal.parse('5.78'), currency: "USD"),
internalComponents: [
// Optional.
ECommerceAmount(amount: Decimal.parse('30570000'), currency: "wood"),
ECommerceAmount(amount: Decimal.parse('26.89'), currency: "iron"),
ECommerceAmount(amount: Decimal.parse('5.1'), currency: "gold"),
]);
// Creating a product object.
ECommerceProduct product = ECommerceProduct(
sku: "779213",
name: "Danissimo curd product 5.9%, 130 g", // Optional.
actualPrice: actualPrice, // Optional.
originalPrice: originalPrice, // Optional.
promocodes: ["BT79IYX", "UT5412EP"], // Optional.
payload: payload, // Optional.
categoriesPath: [
"Groceries",
"Dairy",
"Yogurts"
] // Optional.
);
ECommerceReferrer referrer = ECommerceReferrer(
type: "button", // Optional.
identifier: "76890", // Optional.
screen: screen // Optional.
);
// Creating a cartItem object.
ECommerceCartItem addedItems1 = ECommerceCartItem(
product: product,
revenue: actualPrice,
quantity: Decimal.parse("1.0"),
referrer: referrer // Optional.
);
// Creating an order object.
ECommerceOrder order = ECommerceOrder(
identifier: "88528768",
items: [addedItems1],
payload: payload // Optional.
);
ECommerceEvent beginCheckoutEvent = ECommerce.beginCheckoutEvent(order);
// Sending an e-commerce event.
AppMetrica.getReporter("Testing API key")
.reportECommerce(beginCheckoutEvent);
ECommerceEvent purchaseEvent = ECommerce.purchaseEvent(order);
// Sending an e-commerce event.
AppMetrica.getReporter("Testing API key").reportECommerce(purchaseEvent);
Step 3. 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. To learn more about these reports, see Purchase analysis.
Step 4. Configure sending ECommerce to the main API Key
After successful testing, configure sending E-commerce events to the main API key.
To send the ECommerceEvent
object to the main API key, use the AppMetrica.reportECommerce(ECommerceEvent event)
method:
...
// Sending an E-commerce event.
AppMetrica.reportECommerce(ecommerceEvent);
Sending in-app purchases
With validation
To validate purchases on Android, configure sending the Revenue.Receipt
instance along with Revenue. For iOS, configure sending the transactionID
field.
- Create an
AppMetricaReceipt
instance with information about the purchase and signature. - Create an
AppMetricaRevenue
instance and pass theAppMetricaReceipt
andtransactionID
to it. - Send the
AppMetricaRevenue
instance using theAppMetrica.reportRevenue(AppMetricaRevenue revenue)
method.
AppMetricaReceipt receipt = AppMetricaReceipt(
data: billingClientPurchase.originalJson,
signature: billingClientPurchase.signature);
AppMetricaRevenue revenue = AppMetricaRevenue(
Decimal.parse("100.100"),
"USD",
quantity: 2,
productId: "com.yandex.service.299",
payload: "{\"source\":\"Google Play\"}",
receipt: receipt,
transactionId: transactionIdentifier);
AppMetrica.reportRevenue(revenue);
Without validation
-
Create an
AppMetricaRevenue
instance. -
(Optional) To group purchases by
OrderID
, pass it to thepayload
property.
Note
If the OrderID
is not specified, AppMetrica generates the ID automatically.
- Send the
AppMetricaRevenue
instance using theAppMetrica.reportRevenue(AppMetricaRevenue revenue)
method.
AppMetricaRevenue revenue = AppMetricaRevenue(Decimal.parse("100.100"), "USD",
quantity: 2,
productId: "com.yandex.service.299",
payload: """{"OrderID":"Identifier", "source":"Google Play"}""");
AppMetrica.reportRevenue(revenue);
Sending Ad Revenue data on Flutter
Step 1. Make sure that the SDK is activated
Activation example:
AppMetricaConfig config = AppMetricaConfig("API_KEY");
AppMetrica.activate(config);
Step 2. Set up sending ad revenue data
-
Create a
PluginErrorDetails
instance.Map<String, String> adRevenuePayload = { "payload_key_1": "payload_value_1", "payload_key_2": "payload_value_2" }; AdRevenue adRevenue = AdRevenue( adRevenue: Decimal.parse("100.100"), currency: "USD", adNetwork: "ad_network", // Optional adPlacementId: "ad_placement_id", // Optional adPlacementName: "ad_placement_name", // Optional adType: AdType.NATIVE, // Optional adUnitId: "ad_unit_id", // Optional adUnitName: "ad_unit_name", // Optional precision: "some precision", // Optional payload: adRevenuePayload // Optional );
-
Send the
AdRevenue
instance using thereportAdRevenue(AdRevenue);
method.AppMetrica.reportAdRevenue(adRevenue);
Step 3. Make sure that the ad revenue data is included in the reports
-
View ads in the app.
-
Make sure that the Revenue report shows the same number of ad revenue events as the number of ad views.
Tracking app opens using deeplinks
Use the reportAppOpen(String deeplink)
method to track app launches:
AppMetrica.reportAppOpen(deeplink);
Getting AppMetrica SDK IDs
To get AppMetrica SDK IDs (DeviceId
, DeviceIdHash
, UUID
), use the requestStartupParams()
method. To get the appmetrica_device_id
, make sure to request the DeviceIdHash
.
Future<AppMetricaStartupParams> params = AppMetrica.requestStartupParams([
AppMetricaStartupParams.deviceIdHashKey,
AppMetricaStartupParams.deviceIdKey,
AppMetricaStartupParams.uuidKey
]);
params.then((value) => {
print(value.result?.deviceIdHash),
print(value.result?.deviceId),
print(value.result?.uuid)
});
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.