Disable Google Analytics when in development

2019-04-06 12:09发布

My question is pretty simple: is there any way for Google Analytics to be disabled automatically when the application is signed with the debug certificate? Means it should be active only in release version. Thank you in advance.

3条回答
狗以群分
2楼-- · 2019-04-06 12:32

Well you can set it to not be active easily enough:

if (...) {
  GoogleAnalytics ga= GoogleAnalytics.getInstance(getApplicationContext());
  ga.setAppOptOut(true);
}

I usually just check the hardware serial number of some known devices used for testing:

if (Arrays.asList("x", "y").contains(getHardwareSerial()))

Where getHardwareSerial() is:

public static String getHardwareSerial() {
        try {
            Field serialField = Build.class.getDeclaredField("SERIAL");
            return (String) serialField.get(null);
        } catch (NoSuchFieldException nsf) {
        } catch (IllegalAccessException ia) {
        }
        return Build.UNKNOWN;
    }
查看更多
男人必须洒脱
3楼-- · 2019-04-06 12:41

If you're using ADT 17 and above, you can utilize the BuildConfig class:

if(BuildConfig.DEBUG) {
    GoogleAnalytics googleAnalytics = GoogleAnalytics.getInstance(getApplicationContext());
    googleAnalytics.setAppOptOut(true);
}

The BuildConfig class is automatically generated like R.java is. It only contains the DEBUG boolean, which is set to true by default, and to false when you export an apk.

查看更多
Emotional °昔
4楼-- · 2019-04-06 12:52

With the latest version of Google Analytics, you should be using the following code:

if(BuildConfig.DEBUG){
    GoogleAnalytics.getInstance(this).setDryRun(true);
}
查看更多
登录 后发表回答