Google Analytics 为我的 Android 应用程序选择了错误的版本号

Posted

技术标签:

【中文标题】Google Analytics 为我的 Android 应用程序选择了错误的版本号【英文标题】:Google Analytics picking up wrong version number for my Android App 【发布时间】:2015-09-03 02:56:01 【问题描述】:

我正在我的应用中添加 Google Analytics。当我转到Real Time > Overview 时,我在App Version 下看到1.0。我的问题是 Google Analytics 从哪里得到这个 1.0 号码?

这就是我在启动器 ActivityonCreate() 中启动 Analytics 的方式:

        analytics = GoogleAnalytics.getInstance(MainDrawerActivity.this);
        analytics.setLocalDispatchPeriod(1800);

        tracker = analytics.newTracker("UA-XXXXXX-X"); // Replace with actual tracker/property Id
        tracker.enableExceptionReporting(true);
        tracker.enableAdvertisingIdCollection(true);
        tracker.enableAutoActivityTracking(true);

我的项目有多个 gradle 文件。我将它们全部粘贴在这里:

这是我的 gradle 文件,也是我的 android 清单: build.gradle:(对于我的项目:xxx...)

buildscript 
repositories 
    jcenter()

dependencies 
    classpath 'com.android.tools.build:gradle:1.1.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files



allprojects 
repositories 
    jcenter()


build.gradle:(对于我的模块:app)

android 
compileSdkVersion 22
buildToolsVersion "22.0.0"

defaultConfig 
    applicationId "xxx.xxx.xxx"
    minSdkVersion 16
    targetSdkVersion 22
    versionCode 58
    versionName "2.0.13"

buildTypes 
    release 
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    


compileOptions 
    encoding "UTF-8"
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7

lintOptions 
    abortOnError false


build.gradle for Module: circularImageView(这是一个库项目) 应用插件:'com.android.library'

android 
compileSdkVersion 22
buildToolsVersion "22.0.0"

defaultConfig 
    minSdkVersion 11
    targetSdkVersion 19

    versionCode 60
    versionName "2.0.14"


buildTypes 
    release 
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    


我的清单开始

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xxx.xxxx.xxxxxxxx"
android:installLocation="internalOnly"
android:versionCode="58"
android:versionName="2.0.13" >

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="21" />

另一点需要注意的是——在看到“1.0”版本之前,我在 Eclipse 中,但这是我第一次使用 Android Studio,但我使用the Gradle Method 将 Google Analytics 添加到我的帐户。

【问题讨论】:

你使用全局追踪器吗? 什么是全局跟踪器? 只是一个简短的描述,全局跟踪器永远不会选择错误的应用程序版本名称。我将在答案中描述它。 【参考方案1】:

它从传递给GoogleAnalytics.getInstance(context)的上下文中获取版本

PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
packageInfo.versionName;

根据PackageInfo的文档:

此包的版本名称,由标记的 versionName 属性指定。

此外,为了准确获取您的应用程序数据,您应该从扩展 Application 的类创建 Tracker

public class MyApp extends Application 
    public Tracker tracker;
    .....

    public Tracker getTracker() 
        if (tracker == null) 
            tracker = GoogleAnalytics.getInstance(this);
            .......
        
        return tracker;
     

【讨论】:

传递给此函数的context 是来自我的各种活动的getApplicationContext()。所以我的下一个问题是getApplicationContext() 从哪里获取版本?基本上,它不应该是 1.0,我希望它是 2.0.13(如我的 Manifest 和 build.gradle 所示。 @user1406716 - 我已经尝试了几种不同的方法,分析总是为我从 build.gradle 中提取 versionName。 对不起,我仍然有问题。为问题添加了赏金,还添加了有关我的项目的更多详细信息。如果您有任何其他输入,请告诉我。 @user1406716 - 我已更新我的答案以包含更多信息。这显示了如何检索版本代码。【参考方案2】:

您可以使用 Google Analytics v4 提供的全局跟踪器。在开始在应用中添加全局跟踪器之前,让我们先了解一下这个结构:

app_tracker.xml

<resources>
        <!-- The apps Analytics Tracking Id -->
        <string name="ga_trackingId">UX-XXXXXXXXX-X</string>
        <!-- Percentage of events to include in reports -->
        <string name="ga_sampleFrequency">100.0</string>
        <!-- Enable automatic Activity measurement -->
        <bool name="ga_autoActivityTracking">true</bool>
        <!-- catch and report uncaught exceptions from the app -->
        <bool name="ga_reportUncaughtExceptions">true</bool>
        <!-- How long a session exists before giving up -->
        <integer name="ga_sessionTimeout">-1</integer>
        <!-- If ga_autoActivityTracking is enabled, an alternate screen name can be specified to
        substitute for the full length canonical Activity name in screen view hit. In order to
        specify an alternate screen name use an <screenName> element, with the name attribute
        specifying the canonical name, and the value the alias to use instead. -->
        <screenName name="com.mypackage.example.MainActivity">Home Screen</screenName>
    </resources>

ecommerce_tracker.xml

    <resources>
    <integer name="ga_sessionTimeout">60</integer>
    <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">UX-XXXXXXXXX-X</string>
</resources>

global_tracker.xml

<!-- enter your app's name -->
<string name="ga_appName">My App Name</string>
<!-- enter the current app's versionName -->
<string name="ga_appVersion">2.0.13</string>

<!-- the Local LogLevel for Analytics -->
<string name="ga_logLevel">verbose</string>
<!-- how often the dispatcher should fire -->
<integer name="ga_dispatchPeriod">30</integer>
<!-- Treat events as test events and don't send to google -->
<bool name="ga_dryRun">false</bool>
<!-- The screen names that will appear in reports -->
<screenName name="com.mypackage.example.MainActivity">Home Screen</screenName>

然后,创建一个名为 App 的新 Java 类,并使用 Application 对其进行扩展:

import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import java.util.HashMap;

/**
 * Custom implementation of android.app.Application.&nbsp;The android:name attribute in the
 * AndroidManifest.xml application element should be the name of your class (".MyApp"). Android will
 * always create an instance of the application class and call onCreate before creating any other
 * Activity, Service or BroadcastReceiver.
 */
public class App extends Application 
    // The following line should be changed to include the correct property id.
    private static final String PROPERTY_ID = "UX-XXXXXXXXX-X";

    //Logging TAG
    private static final String TAG = "App";
    public static int GENERAL_TRACKER = 0;

    public enum TrackerName 
        APP_TRACKER, // Tracker used only in this app.
        GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
        ECOMMERCE_TRACKER,
    

    HashMap<TrackerName, Tracker> mTrackers = new HashMap<>();
    public App() 
        super();
    
    public synchronized Tracker getTracker(TrackerName trackerId) 

        if (!mTrackers.containsKey(trackerId)) 
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(R.xml.app_tracker)
            : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(PROPERTY_ID)
            : analytics.newTracker(R.xml.ecommerce_tracker);
            mTrackers.put(trackerId, t);
        
        return mTrackers.get(trackerId);
    

稍微改变你的清单:

<application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">

    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <!-- Google Analytics Version v4 needs this value for easy tracking -->
    <meta-data android:name="com.google.android.gms.analytics.globalConfigResource"
        android:resource="@xml/global_tracker" />

    <!-- Optionally, register AnalyticsReceiver and AnalyticsService to support background
     dispatching on non-Google Play devices -->
    <receiver android:name="com.google.android.gms.analytics.AnalyticsReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
        </intent-filter>
    </receiver>
    <service android:name="com.google.android.gms.analytics.AnalyticsService"
        android:enabled="true"
        android:exported="false"/>

    <!-- Optionally, register CampaignTrackingReceiver and CampaignTrackingService to enable
         installation campaign reporting -->
    <receiver android:name="com.google.android.gms.analytics.CampaignTrackingReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>
    <service android:name="com.google.android.gms.analytics.CampaignTrackingService"
        android:enabled="true"/>

    <!-- ... -->
</application>

最后,在MainActivity 类中点击跟踪器:

private Tracker tracker;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tracker = ((App) getApplication()).getTracker(App.TrackerName.APP_TRACKER);
    tracker.setScreenName("Home Screen");
    tracker.send(new HitBuilders.EventBuilder().build());
    ...


@Override
protected void onStart() 
    super.onStart();
    GoogleAnalytics.getInstance(this).reportActivityStart(this);


@Override
protected void onStop() 
    GoogleAnalytics.getInstance(this).reportActivityStop(this);
    super.onStop();

瞧!谷歌分析已激活!有关详细信息,请参阅:

Advanced Configuration - Android SDK v4

Google Analytics SDK v4 for Android - Getting Started

标签:

适用于 Android 的 Google Analytics(分析)教程 配置谷歌分析 谷歌分析 v4 谷歌分析示例

【讨论】:

以上是关于Google Analytics 为我的 Android 应用程序选择了错误的版本号的主要内容,如果未能解决你的问题,请参考以下文章

Cordova google-analytics-plugin 导致 phonegap iOS 构建失败

带有 Google Analytics API v3 的 OAuth 2.0

Rails ActionView::Template::Error(google_analytics.js 未预编译)

内容安全政策能否与 Google Analytics 和 AdSense 兼容?

从 API 获取 Google Analytics“访客流量”数据

Google Analytics的数据层何时触发,或者,如何测试我的电子商务数据收集脚本?