1

All environment specific keys like server URL and SDK keys are currently kept in the build.gradle file. The purpose of this is to easily switch between developing and production environments using buildTypes.

I added Google Analytics to the app, which is configured via a res/xml/app_tracker.xml file that contains the tracker ID:

<string name="ga_trackingId" translatable="false">UA-12345678-9</string>

How can the tracker ID be moved into the build.gradle file's buildTypes to define a different GA tracker ID for each environment?


Edit

I tried this in build.gradle:

buildTypes {
  release {
    resValue "string", "GOOGLE_ANALYTICS_TRACKER_ID", "UA-12345678-9"
  }
}

Which auto-generates an xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Automatically generated file. DO NOT MODIFY -->

    <!-- Values from build type: debug -->
    <string name="GOOGLE_ANALYTICS_TRACKER_ID" translatable="false">UA-12345678-9</string>

</resources>

But this does not seem to work in the app_tracker.xml file:

<string name="ga_trackingId" translatable="false">@string/GOOGLE_ANALYTICS_TRACKER_ID</string>
Community
  • 1
  • 1
Manuel
  • 14,274
  • 6
  • 57
  • 130
  • Possible duplicate of [How can I access a BuildConfig value in my AndroidManifest.xml file?](https://stackoverflow.com/questions/28954071/how-can-i-access-a-buildconfig-value-in-my-androidmanifest-xml-file) – Morrison Chang Oct 13 '18 at 04:15
  • I tried the solution in your linked answer but it didn't work, that's why I posted this question, see my edit. – Manuel Oct 13 '18 at 12:15

1 Answers1

1

From question you asked, You to want to maintain multiple tracker ids for a different environment.

So instead of maintaining UA-XXX in build.gradle, we need to specify multiple xml files with different UA-XXX in Application class

private static final String PROPERTY_ID = "UA-XXXXX-Y";


  public enum TrackerName {
    PROD_ENV_TRACKER, // Tracker used for Production Environment.
    DEV_ENV_TRACKER, // Tracker used for Devlopment Environment.
    STAGE_ENV_TRACKER, // Tracker used for Stage Environment.
  }

  HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

  public AnalyticsSampleApp() {
    super();
  }
  synchronized Tracker getTracker(TrackerName trackerId) {
    if (!mTrackers.containsKey(trackerId)) {

      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      Tracker t = (trackerId == TrackerName.PROD_ENV_TRACKER) ? analytics.newTracker(PROPERTY_ID)
          : (trackerId == TrackerName.DEV_ENV_TRACKER) ? analytics.newTracker(R.xml.dev_env_tracker)
              : analytics.newTracker(R.xml.stage_env_tracker);
      mTrackers.put(trackerId, t);

    }
    return mTrackers.get(trackerId);
  }
}
ANAND SONI
  • 625
  • 9
  • 13