Campaign Measurement

This document provides an overview of how to measure campaigns and traffic sources with the Google Analytics SDK v4 for Android.

Overview

Measuring campaigns in Google Analytics enables the attribution of campaigns and traffic sources to user activity within your application. These options are available for campaign and traffic source attribution in the Google Analytics SDK v4 for Android:

The following sections will describe when and how to implement each type of campaign measurement in your app.

Google Play Campaign Attribution

Google Play Campaign Measurement allows you to see which campaigns and traffic sources are sending users to download your app from the Google Play Store. It is recommended that all developers implement Google Play Store Campaign Measurement.

Implement Google Play Campaign Attribution

The Google Play Store provides an Install Referrer API for developers to securely retrieve referral content from Google Play. This API returns the value of the referrer parameter used to reach your app’s Google Play Store page, if one was present.

To attribute an app download to a campaign, you must add a referrer parameter to any links that point to Google Play Store, and add Play’s Install Referrer API to your app to receive and set the campaign information contained in the intent on your Google Analytics tracker.

1. Remove the Google Analytics receiver from your AndroidManifest.xml file.

If you also have the Google Tag Manager receiver implemented, remove that from your manifest as well.

2. Add a dependency on the Install Referrer API library.

To add the dependency, include the following in the build.gradle:

dependencies {
    ...
    implementation 'com.android.installreferrer:installreferrer:1.1'
}

3. Call the Install Referrer API in your app’s launch activity.

Use the Install Referrer API to retrieve the referrer URL of the installed app package then pass the URL value to a Google Analytics or Google Tag Manager receiver. Follow a similar implementation to the following code to use the Install Referrer API in your app's launch activity.

If you have multiple entry points into the app, such as deep links into specific parts, you can implement the prescribed methods in an ActivityLifecycleListener that gets triggered by ActivityLifecycleCallbacks.

package com.example.myapplication;

import static com.android.installreferrer.api.InstallReferrerClient.InstallReferrerResponse;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;

import com.android.installreferrer.api.InstallReferrerClient;
import com.android.installreferrer.api.InstallReferrerStateListener;
import com.android.installreferrer.api.ReferrerDetails;
import com.google.android.gms.analytics.CampaignTrackingReceiver;
import com.google.tagmanager.InstallReferrerReceiver;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    private final Executor backgroundExecutor = Executors.newSingleThreadExecutor();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkInstallReferrer();
    }

    // TODO: Change this to use whatever preferences are appropriate. The install referrer should
    // only be sent to the receiver once.
    private final String prefKey = "checkedInstallReferrer";

    void checkInstallReferrer() {
        if (getPreferences(MODE_PRIVATE).getBoolean(prefKey, false)) {
            return;
        }

        InstallReferrerClient referrerClient = InstallReferrerClient.newBuilder(this).build();
        backgroundExecutor.execute(() -> getInstallReferrerFromClient(referrerClient));
    }

    void getInstallReferrerFromClient(InstallReferrerClient referrerClient) {

        referrerClient.startConnection(new InstallReferrerStateListener() {
            @Override
            public void onInstallReferrerSetupFinished(int responseCode) {
                switch (responseCode) {
                    case InstallReferrerResponse.OK:
                        ReferrerDetails response = null;
                        try {
                            response = referrerClient.getInstallReferrer();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            return;
                        }
                        final String referrerUrl = response.getInstallReferrer();


                        // TODO: If you're using GTM, call trackInstallReferrerforGTM instead.
                        trackInstallReferrer(referrerUrl);


                        // Only check this once.
                        getPreferences(MODE_PRIVATE).edit().putBoolean(prefKey, true).commit();

                        // End the connection
                        referrerClient.endConnection();

                        break;
                    case InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
                        // API not available on the current Play Store app.
                        break;
                    case InstallReferrerResponse.SERVICE_UNAVAILABLE:
                        // Connection couldn't be established.
                        break;
                }
            }

            @Override
            public void onInstallReferrerServiceDisconnected() {

            }
        });
    }

    // Tracker for Classic GA (call this if you are using Classic GA only)
    private void trackInstallReferrer(final String referrerUrl) {
        new Handler(getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                CampaignTrackingReceiver receiver = new CampaignTrackingReceiver();
                Intent intent = new Intent("com.android.vending.INSTALL_REFERRER");
                intent.putExtra("referrer", referrerUrl);
                receiver.onReceive(getApplicationContext(), intent);
            }
        });
    }

    // Tracker for GTM + Classic GA (call this if you are using GTM + Classic GA only)
    private void trackInstallReferrerforGTM(final String referrerUrl) {
        new Handler(getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                InstallReferrerReceiver receiver = new InstallReferrerReceiver();
                Intent intent = new Intent("com.android.vending.INSTALL_REFERRER");
                intent.putExtra("referrer", referrerUrl);
                receiver.onReceive(getApplicationContext(), intent);
            }
        });
    }

}

4. Add Google Analytics Campaign Parameters to Google Play URLs

Next, add a referrer parameter to any URLs that will be linking directly to Google Play Store and set the value of that parameter to a string of Google Analytics campaign parameters that describe the source, as in this example:

https://play.google.com/store/apps/details?id=com.example.application
&referrer=utm_source%3Dgoogle
%26utm_medium%3Dcpc
%26utm_term%3Drunning%252Bshoes
%26utm_content%3Dlogolink
%26utm_campaign%3Dspring_sale

To learn how to build a campaign parameter strings, use the Google Play URL Builder, or consult the Campaign Parameters reference section.

General Campaign & Traffic Source Attribution

After an app has been installed, it may be launched by referrals from ad campaigns, websites, or other apps. In this scenario, referring traffic sources or marketing campaigns may be attributed to user activity in subsequent sessions by setting the campaign parameters on a tracker directly by using the setCampaignParamsFromUrl method.

// Get tracker.
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
    TrackerName.APP_TRACKER);

// Set screen name.
t.setScreenName(screenName);

// In this example, campaign information is set using
// a url string with Google Analytics campaign parameters.
// Note: This is for illustrative purposes. In most cases campaign
//       information would come from an incoming Intent.
String campaignData = "http://examplepetstore.com/index.html?" +
    "utm_source=email&utm_medium=email_marketing&utm_campaign=summer" +
    "&utm_content=email_variation_1";

// Campaign data sent with this hit.
t.send(new HitBuilders.ScreenViewBuilder()
    .setCampaignParamsFromUrl(campaignData)
    .build()
);

See Advanced Configuration for details on the getTracker method.

Campaign Parameters

Campaign parameters are used to pass information about the traffic sources and campaigns that are bringing users to your app.

The table below contains the available campaign parameters that can be used in Google Play or general campaign measurement:

Parameter Description Example(s)
utm_source Campaign source; used to identify a search engine, newsletter, or other source utm_source=google
utm_medium Campaign medium; used to identify a medium such as email or cost-per-click (cpc) utm_medium=cpc
utm_term Campaign term; used with paid search to supply the keywords for ads utm_term=running+shoes
utm_content Campaign content; used for A/B testing and content-targeted ads to differentiate ads or links that point to the same URL utm_content=logolink
utm_content=textlink
utm_campaign Campaign name; used for keyword analysis to identify a specific product promotion or strategic campaign utm_campaign=spring_sale
gclid Google Ads autotagging parameter; used to measure ads. This value is generated dynamically and should never be modified.

Google Play URL Builder

Use the tool below to generate URLs for Google Play Campaign Measurement.