Google Analytics for Android无法正常运行

时间:2016-12-14 05:50:46

标签: android firebase google-analytics

我正在开发一款Android应用。我正在尝试将Google Analytics与我的Android应用集成。我正在跟踪我的应用程序访问过的页面但数据不会从应用程序发送到Google Analytics控制台/信息中心。请看下面我做了什么。

  1. 我已将Firebase推送通知集成到我的应用中。所以我不需要添加json文件。

  2. 我将自己的应用程序从Firebase注册到Google Analytics,我获得了一个唯一的跟踪ID。

  3. 然后在我的应用程序类中,我创建了这样的跟踪器实例。

  4. public class MApplication extends Application {
    
            public static final String GOOGLE_TRACK_ID ="MY-TRACK-ID";
            public static GoogleAnalytics analytics;
            public static Tracker tracker;
    
            @Override
            public void onCreate() {
                super.onCreate();
                analytics = GoogleAnalytics.getInstance(this);
                analytics.setLocalDispatchPeriod(1800);
                tracker = analytics.newTracker(GOOGLE_TRACK_ID);
                tracker.enableExceptionReporting(true);
                tracker.enableAdvertisingIdCollection(true);
                tracker.enableAutoActivityTracking(true);
            }
    
        }
    

    我启动了这样的跟踪器,因为我找不到XML文件。所以我找到了这个解决方案 - Android Google Analytics xml file。这就是我实例化的原因。

    1. 然后在我要跟踪的页面中,我发送这样的数据。
    2. mApplication.tracker.setScreenName("Articles Page");
                      mApplication.tracker.send(new HitBuilders.ScreenViewBuilder().build());
      

      这是我的清单文件

      <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.football.waiyanhein.tonightfootballreport">
      
          <uses-permission android:name="android.permission.INTERNET" />
          <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
          <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
          <uses-feature android:name="android.hardware.camera" />
          <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
          <uses-permission android:name="android.permission.CAMERA" />
          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      
          <application
              android:name="com.football.waiyanhein.model.MApplication"
              android:allowBackup="true"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:supportsRtl="true"
              android:theme="@style/AppTheme.NoActionBar">
              <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
              <activity android:name="com.football.waiyanhein.tonightfootballreport.StartActivity"
                  android:configChanges="orientation|screenSize"
                  android:noHistory="true">
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
              //Other activities go here
      
              <provider android:authorities="com.facebook.app.FacebookContentProvider1864111377153297"
                  android:name="com.facebook.FacebookContentProvider"
                  android:exported="true"/>
      
              <receiver android:name="com.football.waiyanhein.receiver.NotificationReceiver">
                  <intent-filter>
                      <action android:name="com.tonightfootball.waiyanhein.receiver.NotificationReceiver"></action>
                  </intent-filter>
              </receiver>
              <receiver android:name="com.football.waiyanhein.receiver.MemeCreateReceiver">
                  <intent-filter>
                      <action android:name="com.tonightfootball.waiyanhein.receiver.MemeCreateReceiver"></action>
                  </intent-filter>
              </receiver>
      
      
              <service android:name="com.football.waiyanhein.service.MyFirebaseMessagingService">
                  <intent-filter>
                      <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                  </intent-filter>
              </service>
              <service android:name="com.football.waiyanhein.service.FirebaseIDService">
                  <intent-filter>
                      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
                  </intent-filter>
              </service>
          </application>
      
      </manifest>
      

      没有数据发送,你可以在这里看到。

      enter image description here

      当我查看Analytics Dashboard时,没有用户数据,Analytics Dashboard中没有发送任何内容。为什么它不起作用?

3 个答案:

答案 0 :(得分:1)

尝试使用以下Code snippest进行Google分析

添加 build.gradle

 dependencies {
    compile 'com.google.android.gms:play-services-analytics:9.2.0'
 }

添加Java类 AnalyticsTrackers.java

package com.nitin.tracker;

import android.content.Context;

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


public final class AnalyticsTrackers {

 public enum Target {
    APP,
    // Add more trackers here if you need, and update the code in #get(Target) below
 }

private static AnalyticsTrackers sInstance;

public static synchronized void initialize(Context context) {
    if (sInstance != null) {
        throw new IllegalStateException("Extra call to initialize analytics trackers");
    }

    sInstance = new AnalyticsTrackers(context);
}

public static synchronized AnalyticsTrackers getInstance() {
    if (sInstance == null) {
        throw new IllegalStateException("Call initialize() before getInstance()");
    }

    return sInstance;
}

private final Map<Target, Tracker> mTrackers = new HashMap<Target, Tracker>();
private final Context mContext;

/**
 * Don't instantiate directly - use {@link #getInstance()} instead.
 */
private AnalyticsTrackers(Context context) {
    mContext = context.getApplicationContext();
}

public synchronized Tracker get(Target target) {
    if (!mTrackers.containsKey(target)) {
        Tracker tracker;
        switch (target) {
            case APP:
                tracker = GoogleAnalytics.getInstance(mContext).newTracker(R.xml.app_tracker);
                break;
            default:
                throw new IllegalArgumentException("Unhandled analytics target " + target);
        }
        mTrackers.put(target, tracker);
    }

    return mTrackers.get(target);
}
}

添加 res / xml / app_tracker.xml

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
 <!-- End current session if app sleeps for a period of time -->
<integer name="ga_sessionTimeout">300</integer>

<!-- Enable automatic Activity measurement -->
<bool name="ga_autoActivityTracking">true</bool>

<!--  The property id associated with this analytics tracker -->
<string name="ga_trackingId">UA-12345678-2</string>

<string name="ga_sampleFrequency">100.0</string>

<bool name="ga_reportUncaughtExceptions">true</bool>
</resources>

创建扩展应用程序类,如 MyApplication .java

package com.nitin.tracker;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.multidex.MultiDex;  
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.StandardExceptionParser;
import com.google.android.gms.analytics.Tracker;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;

public class MyApplication extends Application {

public static final String TAG = MyApplication.class
        .getSimpleName();

private static MyApplication mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;

    AnalyticsTrackers.initialize(this);
    AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);
}

public static synchronized MyApplication getInstance() {
    return mInstance;
}

public synchronized Tracker getGoogleAnalyticsTracker() {
    AnalyticsTrackers analyticsTrackers = AnalyticsTrackers.getInstance();
    return analyticsTrackers.get(AnalyticsTrackers.Target.APP);
}


public void trackScreenView(String screenName) {

        Tracker t = getGoogleAnalyticsTracker();
        // Set screen name.
        t.setScreenName(screenName);
        // Send a screen view.
        t.send(new HitBuilders.ScreenViewBuilder().build());
        GoogleAnalytics.getInstance(this).dispatchLocalHits();

}

public void trackException(Exception e) {
    if (e != null) {
        Tracker t = getGoogleAnalyticsTracker();

        t.send(new HitBuilders.ExceptionBuilder()
                .setDescription(
                        new StandardExceptionParser(this, null)
                                .getDescription(Thread.currentThread().getName(), e))
                .setFatal(false)
                .build()
        );
    }
}


public void trackEvent(String category, String action, String label) {
    Tracker t = getGoogleAnalyticsTracker();

    // Build and send an Event.
    t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
}
}

添加 manifestast.xml

<application
    android:name="com.nitin.tracker.MyApplication">
  <!-- Analytics Permission -->
    <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" />

如果您想跟踪屏幕通话

@Override
protected void onResume() {
    super.onResume();
    MyApplication.getInstance().trackScreenView("Screen Name");
}

如果您想跟踪活动

 MyApplication.getInstance().trackEvent("Module", "Event Name", "Operation of event");

它为我工作。我希望它对你有所帮助。

答案 1 :(得分:1)

请尝试此操作,确保您的跟踪ID有效。

public class MApplication extends Application {

        public static final String GOOGLE_TRACK_ID ="MY-TRACK-ID";
        public static GoogleAnalytics analytics;
        public static Tracker tracker;

        @Override
        public void onCreate() {
            super.onCreate();
            getDefaultTracker();

        }

synchronized public void getDefaultTracker() {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.setLocalDispatchPeriod(1800);
            tracker = analytics.newTracker(GOOGLE_TRACK_ID);
            tracker.enableExceptionReporting(true);
            tracker.enableAdvertisingIdCollection(true);
            tracker.enableAutoActivityTracking(true);

    }

答案 2 :(得分:0)

您可以尝试在需要跟踪的活动中添加以下代码行,而不是使用tracker.send()。

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

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