使用Google Analytics跟踪碎片

时间:2021-06-16 15:18:20

Just need to know the proper way to implement Google analytics to track when a user is on a fragment in real time this is what is do now

只需知道实施Google分析的正确方法,即可实时跟踪用户何时处于片段状态

@Override
public void onResume() {
    super.onResume();
    Tracker myTracker = parentActivity.getTracker();
    myTracker.setCustomMetric(1, (long) 1);               
    myTracker.sendView("Music View"); 
}

the getTracker class is in my main activity and just returns the instance of tracker in the main activity

getTracker类在我的主要活动中,只返回主活动中的跟踪器实例

Any help would be much appreciated!

任何帮助将非常感激!

6 个解决方案

#1


46  

Mochini's answer uses Google Analytics V2. Bellow you can see how to do it on V4 and V3:

Mochini的答案使用Google Analytics V2。 Bellow你可以看到如何在V4和V3上做到这一点:

  • V4:

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 (you can name it anything, it does not need to be called "analytics")

res / xml / analytics.xml(你可以命名它,它不需要被称为“分析”)

<?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'

Fragment superclass:

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() );
         }
    }
    
  • V3导入android.os.Bundle; import android.support.v4.app.Fragment; 导入com.google.analytics.tracking.android.EasyTracker; 导入com.google.analytics.tracking.android.Fields; import com.google.analytics.tracking.android.MapBuilder; import com.google.analytics.tracking.android.Tracker; 公共抽象类TrackedFragment扩展Fragment {      私人追踪器追踪器;      @覆盖      public void onActivityCreated(final Bundle savedInstanceState){          super.onActivityCreated(savedInstanceState);          this.tracker = EasyTracker.getInstance(getActivity());      }      @覆盖      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

#2


10  

This an example using FragmentActivity and fragments:

这是一个使用FragmentActivity和片段的例子:

  1. Create XML file in value folder (values/analytics.xml):

    在值文件夹(values / analytics.xml)中创建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>
    
  2. In your FragmentActivity class, add this:

    在FragmentActivity类中,添加以下内容:

    @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
    }
    
  3. Create new class in your package: TrackedFragment.java

    在包中创建新类: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);
        }
    }
    
  4. Finally, your fragment should extend from TrackedFragment like:

    最后,您的片段应该从TrackedFragment扩展,如:

    public class NewFragment extends TrackedFragment {
    
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.newfragment, null);
        }
    
    }
    

#3


3  

Tracking methods section suggests that you just need to call EasyTracker.getInstance().setContext(getActivity()); first, then you can use the tracker in "other classes".

跟踪方法部分建议您只需要调用EasyTracker.getInstance()。setContext(getActivity());首先,您可以在“其他类”中使用跟踪器。

manual screen tracking section suggests that you can track a Fragment view with myTracker.sendView("Home Screen");

手动屏幕跟踪部分建议您可以使用myTracker.sendView跟踪片段视图(“主屏幕”);

#4


3  

Another approach for V3 (since onResume() is tied to the Activity and not the Fragment. This works well when the parent/child relationships are well-known.

V3的另一种方法(因为onResume()与Activity而不是Fragment绑定。当父/子关系众所周知时,这种方法很有效。

Parent Fragment sends initial event onStart():

Parent Fragment发送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());
    }
}

Child Fragment overrides both onStart() and onStop() :

子片段覆盖onStart()和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());
    }
}

#5


2  

Tiago's version can't be used in the new goole analytics v4. Instead, use this code from Google's docs

Tiago的版本不能用于新的goole分析v4。相反,请使用Google文档中的此代码

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());
      }
    });
  }
}

#6


1  

with android google analytics v4

用android google analytics v4

i tried this and it worked

我试过这个并且它有效

refering this https://developers.google.com/analytics/devguides/collection/android/v4/events

参考此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;
      }
}

#1


46  

Mochini's answer uses Google Analytics V2. Bellow you can see how to do it on V4 and V3:

Mochini的答案使用Google Analytics V2。 Bellow你可以看到如何在V4和V3上做到这一点:

  • V4:

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 (you can name it anything, it does not need to be called "analytics")

res / xml / analytics.xml(你可以命名它,它不需要被称为“分析”)

<?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'

Fragment superclass:

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() );
         }
    }
    
  • V3导入android.os.Bundle; import android.support.v4.app.Fragment; 导入com.google.analytics.tracking.android.EasyTracker; 导入com.google.analytics.tracking.android.Fields; import com.google.analytics.tracking.android.MapBuilder; import com.google.analytics.tracking.android.Tracker; 公共抽象类TrackedFragment扩展Fragment {      私人追踪器追踪器;      @覆盖      public void onActivityCreated(final Bundle savedInstanceState){          super.onActivityCreated(savedInstanceState);          this.tracker = EasyTracker.getInstance(getActivity());      }      @覆盖      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

#2


10  

This an example using FragmentActivity and fragments:

这是一个使用FragmentActivity和片段的例子:

  1. Create XML file in value folder (values/analytics.xml):

    在值文件夹(values / analytics.xml)中创建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>
    
  2. In your FragmentActivity class, add this:

    在FragmentActivity类中,添加以下内容:

    @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
    }
    
  3. Create new class in your package: TrackedFragment.java

    在包中创建新类: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);
        }
    }
    
  4. Finally, your fragment should extend from TrackedFragment like:

    最后,您的片段应该从TrackedFragment扩展,如:

    public class NewFragment extends TrackedFragment {
    
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.newfragment, null);
        }
    
    }
    

#3


3  

Tracking methods section suggests that you just need to call EasyTracker.getInstance().setContext(getActivity()); first, then you can use the tracker in "other classes".

跟踪方法部分建议您只需要调用EasyTracker.getInstance()。setContext(getActivity());首先,您可以在“其他类”中使用跟踪器。

manual screen tracking section suggests that you can track a Fragment view with myTracker.sendView("Home Screen");

手动屏幕跟踪部分建议您可以使用myTracker.sendView跟踪片段视图(“主屏幕”);

#4


3  

Another approach for V3 (since onResume() is tied to the Activity and not the Fragment. This works well when the parent/child relationships are well-known.

V3的另一种方法(因为onResume()与Activity而不是Fragment绑定。当父/子关系众所周知时,这种方法很有效。

Parent Fragment sends initial event onStart():

Parent Fragment发送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());
    }
}

Child Fragment overrides both onStart() and onStop() :

子片段覆盖onStart()和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());
    }
}

#5


2  

Tiago's version can't be used in the new goole analytics v4. Instead, use this code from Google's docs

Tiago的版本不能用于新的goole分析v4。相反,请使用Google文档中的此代码

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());
      }
    });
  }
}

#6


1  

with android google analytics v4

用android google analytics v4

i tried this and it worked

我试过这个并且它有效

refering this https://developers.google.com/analytics/devguides/collection/android/v4/events

参考此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;
      }
}