Il suffit de connaître la bonne façon d'implémenter Google Analytics pour suivre quand un utilisateur est sur un fragment en temps réel, c'est ce que l'on fait maintenant
@Override
public void onResume() {
super.onResume();
Tracker myTracker = parentActivity.getTracker();
myTracker.setCustomMetric(1, (long) 1);
myTracker.sendView("Music View");
}
la classe getTracker est dans mon activité principale et renvoie juste l'instance de tracker dans l'activité principale
Toute aide serait très appréciée!
La réponse de Mochini utilise Google Analytics V2. Ci-dessous, vous pouvez voir comment le faire sur V4 et V3:
Application:
public class YourApplication extends Application
{
public synchronized Tracker getTracker() {
try {
final GoogleAnalytics googleAnalytics = GoogleAnalytics.getInstance(this);
return googleAnalytics.newTracker(R.xml.analytics);
}catch(final Exception e){
Log.e(TAG, "Failed to initialize Google Analytics V4");
}
return null;
}
}
res/xml/analytics.xml (vous pouvez tout nommer, il n'a pas besoin d'être appelé "analytics")
<?xml version="1.0" encoding="utf-8" ?>
<resources xmlns:tools="http://schemas.Android.com/tools" tools:ignore="TypographyDashes">
<!--Replace placeholder ID with your tracking ID-->
<string name="ga_trackingId">UA-XXXXXXXX-X</string>
<!--Enable automatic activity tracking-->
<bool name="ga_autoActivityTracking">true</bool>
<!--Disable automatic exception tracking-->
<bool name="ga_reportUncaughtExceptions">false</bool>
</resources>
build.gradle:
compile 'com.google.Android.gms:play-services:7.3.0'
Superclasse de fragments:
public abstract class TrackedFragment extends Fragment{
@Override
public void onResume() {
super.onResume();
final Tracker tracker = yourApplicationInstance.getTracker();
if(tracker != null){
tracker.setScreenName(getClass().getSimpleName());
tracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
}
V3
import Android.os.Bundle;
import Android.support.v4.app.Fragment;
import com.google.analytics.tracking.Android.EasyTracker;
import com.google.analytics.tracking.Android.Fields;
import com.google.analytics.tracking.Android.MapBuilder;
import com.google.analytics.tracking.Android.Tracker;
public abstract class TrackedFragment extends Fragment{
private Tracker tracker;
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.tracker = EasyTracker.getInstance(getActivity());
}
@Override
public void onResume() {
super.onResume();
this.tracker.set(Fields.SCREEN_NAME, getClass().getSimpleName());
this.tracker.send( MapBuilder.createAppView().build() );
}
}
Source: https://developers.google.com/analytics/devguides/collection/Android/v3/migration
Voici un exemple utilisant FragmentActivity
et des fragments:
Créer un fichier XML dans le dossier de valeurs (values/analytics.xml
):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Replace placeholder ID with your tracking ID -->
<string name="ga_trackingId">XX-xxxxxxxx-x</string>
<!-- Enable Activity tracking -->
<bool name="ga_autoActivityTracking">true</bool>
<!-- Enable debug -->
<bool name="ga_debug">true</bool>
<!-- The screen names that will appear in your reporting -->
<string name="com.example.myapp.FragmentActivity">Fragment activity</string>
<!--
The inverval of time after all the collected data
should be sent to the server, in seconds.
-->
<integer name="ga_dispatchPeriod">20</integer>
</resources>
Dans votre classe FragmentActivity
, ajoutez ceci:
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().setContext(this.getBaseContext());
EasyTracker.getInstance().activityStart(this); // Add this method
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this); // Add this method
}
Créez une nouvelle classe dans votre package: TrackedFragment.Java
public class TrackedFragment extends Fragment {
private Tracker tracker;
private String activityId;
private String fragmentId;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EasyTracker.getInstance().setContext(getActivity().getApplicationContext());
this.tracker = EasyTracker.getTracker();
this.fragmentId = getClass().getSimpleName();
this.activityId = getActivity().getClass().getSimpleName();
}
@Override
public void onResume() {
super.onResume();
this.tracker.sendView("/" + this.activityId + "/" + this.fragmentId);
}
}
Enfin, votre fragment devrait s'étendre de TrackedFragment
comme:
public class NewFragment extends TrackedFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.newfragment, null);
}
}
Une autre approche pour V3 (puisque onResume()
est liée à l'activité et non au fragment. Cela fonctionne bien lorsque les relations parent/enfant sont bien connues.
Le fragment parent envoie l'événement initial onStart()
:
public class ParentFragment extends Fragment {
private Tracker mTracker;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTracker = EasyTracker.getInstance(getActivity());
}
@Override
public void onStart() {
super.onStart();
mTracker.set(Fields.SCREEN_NAME, "Parent Fragment");
mTracker.send(MapBuilder.createAppView().build());
}
}
Le fragment enfant remplace onStart()
et onStop()
:
public class ChildFragment extends Fragment {
private Tracker mTracker;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTracker = EasyTracker.getInstance(getActivity());
}
@Override
public void onStart() {
super.onStart();
mTracker.set(Fields.SCREEN_NAME, "Child Fragment");
mTracker.send(MapBuilder.createAppView().build());
}
@Override
public void onStop() {
super.onStop();
mTracker.set(Fields.SCREEN_NAME, "Parent Fragment");
mTracker.send(MapBuilder.createAppView().build());
}
}
section Méthodes de suivi suggère que vous avez juste besoin d'appeler EasyTracker.getInstance().setContext(getActivity());
d'abord, puis vous pouvez utiliser le tracker dans "d'autres classes".
section de suivi d'écran manuel suggère que vous pouvez suivre une vue Fragment
avec myTracker.sendView("Home Screen");
La version de Tiago ne peut pas être utilisée dans la nouvelle goole analytics v4. Utilisez plutôt ce code de Google's docs
package com.google.Android.apps.mobileplayground;
import com.google.Android.apps.mobileplayground.AnalyticsSampleApp.TrackerName;
import com.google.Android.gms.analytics.GoogleAnalytics;
import com.google.Android.gms.analytics.HitBuilders;
import com.google.Android.gms.analytics.Tracker;
import Android.os.Bundle;
import Android.support.v4.app.Fragment;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.view.ViewGroup;
import Android.widget.Button;
/**
* Class to exercise Event hits.
*/
public class EventFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.event, container, false);
setupEvent(view, R.id.video1Play, R.string.videoCategory, R.string.videoPlay, R.string.video1);
setupEvent(view, R.id.video1Pause, R.string.videoCategory, R.string.videoPause,
R.string.video1);
setupEvent(view, R.id.video2Play, R.string.videoCategory, R.string.videoPlay, R.string.video2);
setupEvent(view, R.id.video2Pause, R.string.videoCategory, R.string.videoPause,
R.string.video2);
setupEvent(view, R.id.book1View, R.string.bookCategory, R.string.bookView, R.string.book1);
setupEvent(view, R.id.book1Share, R.string.bookCategory, R.string.bookShare, R.string.book1);
final Button dispatchButton = (Button) view.findViewById(R.id.eventDispatch);
dispatchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Manually start a dispatch (Unnecessary if the tracker has a dispatch interval)
GoogleAnalytics.getInstance(getActivity().getApplicationContext()).dispatchLocalHits();
}
});
return view;
}
private void setupEvent(View v, int buttonId, final int categoryId, final int actionId,
final int labelId) {
final Button pageviewButton = (Button) v.findViewById(buttonId);
pageviewButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Get tracker.
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory(getString(categoryId))
.setAction(getString(actionId))
.setLabel(getString(labelId))
.build());
}
});
}
}
avec Android google analytics v4
je l'ai essayé et ça marche
référant à cela https://developers.google.com/analytics/devguides/collection/Android/v4/events
import Java.net.URLEncoder;
import Android.os.Bundle;
import Android.support.v4.app.Fragment;
import Android.util.Xml.Encoding;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;
import Android.webkit.WebView;
import Android.widget.ScrollView;
import Android.widget.TextView;
import com.Blog.gkgyan.AnalyticsSampleApp.TrackerName;
import com.Blog.gkgyan.parser.RSSFeed;
import com.google.Android.gms.ads.AdRequest;
import com.google.Android.gms.ads.AdView;
import com.google.Android.gms.analytics.GoogleAnalytics;
import com.google.Android.gms.analytics.HitBuilders;
import com.google.Android.gms.analytics.Tracker;
public class DetailFragment extends Fragment {
private int fPos;
RSSFeed fFeed;
String country;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fFeed = (RSSFeed)getArguments().getSerializable("feed");
fPos = getArguments().getInt("pos");
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory(fFeed.getItem(fPos).getTitle())
.setAction("viewpager click")
.setLabel("viewpager label")
.build());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
// Initializr views
TextView title = (TextView)view.findViewById(R.id.title);
WebView desc = (WebView)view.findViewById(R.id.desc);
// Enable the vertical fading Edge (by default it is disabled)
ScrollView sv = (ScrollView)view.findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);
// Set the views
desc.getSettings().setJavaScriptEnabled(true);
title.setText(fFeed.getItem(fPos).getTitle());
country = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><style type=\"text/css\">p{text-align:justify;font-size:125%;}</style></head><body>" + "<p>" + fFeed.getItem(fPos).getDescription()+"</p>"+"</body></html>";
//desc.loadData( country, "text/html", "UTF-8");
//desc.loadData( country, "text/html; charset=utf-8", "utf-8");
desc.loadData( URLEncoder.encode(country).replaceAll("\\+", " "), "text/html", Encoding.UTF_8.toString());
return view;
}
}