我已在我的Android应用程序中集成了Google Analytics V4。它实时跟踪屏幕,但它不跟踪我的应用程序中的事件。我错过了一些代码吗?
public class MyApplication extends Application {
private 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(com.jollyfoodfellow.customclass.AnalyticsTrackers.Target.APP);
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public synchronized Tracker getGoogleAnalyticsTracker() {
AnalyticsTrackers analyticsTracker = AnalyticsTrackers.getInstance();
return analyticsTracker.get(com.jollyfoodfellow.customclass.AnalyticsTrackers.Target.APP);
}
public void trackEvent(String category, String action, String label) {
Log.v(TAG, "##### Track Event is called ######");
Tracker t = getGoogleAnalyticsTracker();
t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
}
}
AnalyticsTracker.java
public 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);
}
}
app_tracker.xml
<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-XXXXXXX-X</string>
<string name="ga_sampleFrequency">100.0</string>
<bool name="ga_reportUncaughtExceptions">true</bool>
</resource>
这是点击事件代码
@Override
public void onClick(View v) {
MyApplication.getInstance().trackEvent(TAG, "Login Clicked", "User clicked on Login button");
}