如何在 Android 应用程序中集成 Google Analytics

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24782901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:45:34  来源:igfitidea点击:

How to integrate Google Analytics in Android app

androidgoogle-analytics

提问by Pravinsingh Waghela

Hi I am trying to integrate the Google Analytics but I am not able to find any analytics data that shows on the Google Analytics Account of mine. I am using the link mention below:-

您好,我正在尝试集成 Google Analytics,但我找不到任何显示在我的 Google Analytics 帐户上的分析数据。我正在使用下面提到的链接:-

developers.google.com link 1

developer.google.com 链接 1

some link 1

一些链接 1

some link 2

一些链接 2

developer.google link 2

developer.google 链接 2

But I am not able to get the result, nor the correct path/way or proper and Detailed Tutorial for how to integrate the Google Analytics in android app.

但我无法获得结果,也无法获得正确的路径/方式或有关如何将 Google Analytics 集成到 android 应用程序的正确详细教程。

My code is as follows:-

我的代码如下:-

    public class MainActivity extends Activity {
    GoogleAnalytics tracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         // Get tracker.
        Tracker t = ((AnalyticsHelper) MainActivity.this.getApplication()).getTracker(
            TrackerName.APP_TRACKER);
     // Set the dispatch period in seconds.
        GAServiceManager.getInstance().setLocalDispatchPeriod(8);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this);
     // Set the dispatch period in seconds.
        GAServiceManager.getInstance().setLocalDispatchPeriod(8);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EasyTracker.getInstance(this).activityStop(this);
    }
}

My Analytics Helper class is as follows:-

我的分析助手类如下:-

public class AnalyticsHelper extends Application {

     // The following line should be changed to include the correct property id.
    private static final String PROPERTY_ID = "UA-xxxxxxxx-x"; // My Property id.

    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, // Tracker used by all ecommerce transactions from a company.
    }

    HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

    public AnalyticsHelper()
    {
        super();
    }

    synchronized Tracker getTracker(TrackerName trackerId) {
        if (!mTrackers.containsKey(trackerId)) {

            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.getLogger().setLogLevel(LogLevel.VERBOSE);
            Tracker t = null;
            if(trackerId==TrackerName.APP_TRACKER){
                t= analytics.getTracker(PROPERTY_ID);
            }
                 mTrackers.put(trackerId, t);
                }
        return mTrackers.get(trackerId);
    }
}

And my analytics xml file in xml directory is as follows:-

我在 xml 目录中的分析 xml 文件如下:-

    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
            tools:ignore="TypographyDashes">

     <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">UA-xxxxxxxx-X</string>

   <!--Enable automatic activity tracking-->
  <bool name="ga_autoActivityTracking">true</bool>

  <!--Enable automatic exception tracking-->
  <bool name="ga_reportUncaughtExceptions">true</bool>

</resources>

Any help will be heart-fully welcomed. Thanks in advance.

任何帮助都会受到热烈欢迎。提前致谢。

采纳答案by Pravinsingh Waghela

Well the above code given in the Question works well. All you need to do is after setting your code and adding the Jar file Download Google Analytics Jar file to your Lib. just wait for 24 to 48 hours. and it would show all the events and analytic for the App you had registered.

那么问题中给出的上述代码效果很好。您需要做的就是在设置代码并添加 Jar 文件之后将Google Analytics Jar 文件下载到您的 Lib。只需等待 24 到 48 小时。它会显示您注册的应用程序的所有事件和分析。

Edited Answer:-

编辑答案:-

Once You had Created your Google Analytic account and Downloaded the Jar file, Add the Jar file in your libfolder of your Application

创建 Google Analytic 帐户并下载 Jar 文件后,将 Jar 文件添加到应用程序的lib文件夹中

Google Analytic Implementation:-

谷歌分析实施:-

Well For Analytic Part You Just need the analytic.xmlfile to be included in your values folder which is mentioned in the Question.

那么对于分析部分,您只需要将analytic.xml文件包含在问题中提到的值文件夹中。

Then define private EasyTracker easyTracker = null;in your MainActivity.

然后private EasyTracker easyTracker = null;在您的MainActivity 中定义。

And now in your onCreate(Bundle savedInstanceState)method just write the following lines of Code. Well you can also write the following code for any Listners e.g. on any Button Click.

现在在您的onCreate(Bundle savedInstanceState)方法中只需编写以下代码行。好吧,您也可以为任何 Listner 编写以下代码,例如在任何 Button Click 上。

    /*
    *For Google Analytics...
    */
    easyTracker = EasyTracker.getInstance(MainActivity.this); // It Tracks your Activity...
    easyTracker.send(MapBuilder.createEvent("SomeValue(StoryPage)",
            "SomeMoreValue(AuthorName) , "SomeMoreValueAgain(StoryTitle)", null).build()); //This line creates the event for keeping logs and other Analytical stuffs concerned to this Activity of Application...
//In the above example we had Tracked the session for the MainActivity and also Analysed how many time this activity was opened, which Author story and which Story was read.

Now in your onStart()Method, just write the following code, it starts the Tracking and Analytics session for your Activity.

现在在您的onStart()方法中,只需编写以下代码,它就会为您的活动启动跟踪和分析会话。

EasyTracker.getInstance(this).activityStart(this);

And now in your onStop()Method, just write the following code, it will close or stop the Tracking session for this activity.

现在在您的onStop()方法中,只需编写以下代码,它将关闭或停止此活动的跟踪会话。

EasyTracker.getInstance(this).activityStop(this);

Now you are able to Track and Analysis your Application and Activities in It.

现在您可以跟踪和分析您的应用程序和其中的活动。

回答by rdmacken

I have detailed the steps for integrating Google Analytics into an existing app here. When I publish a new app I always go back to these instructions which work well.

在此处详细介绍了将 Google Analytics 集成到现有应用程序中的步骤。当我发布一个新的应用程序时,我总是回到这些运行良好的说明。

回答by Venkatesh

  1. Fisrt we have to create google analytics track id Goolge analytics sign in and enable api and get track id

  2. After that put that track id in below .xml code

  1. 首先,我们必须创建 google 分析跟踪 id 谷歌分析登录并启用 api 并获取跟踪 id

  2. 之后将该轨道 ID 放在下面的 .xml 代码中



 <?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="ga_sessionTimeout">300</integer>
<bool name="ga_autoActivityTracking">true</bool>
<string name="ga_trackingId">"place your track id"</string>
<string name="ga_sampleFrequency">100.0</string>
<bool name="ga_reportUncaughtExceptions">true</bool>
<screenName name="com.aquadeals.seller.HomeMainActivity">DashBoard Screen</screenName>

3. After that we can change manifest file very important to add this code below Add permissions

3.之后我们可以更改清单文件非常重要,在添加权限下面添加此代码

4.Change your application name to google analytics class name example"MyApplication.java"

4.将您的应用程序名称更改为 google 分析类名称示例“MyApplication.java”

 <application
    android:name=".app.MyApplication"

5. After that add services for sending and receiving broadcast events using internet

5.然后添加使用互联网发送和接收广播事件的服务

 <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" />
    <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" />
  1. Before this manifest changes first add this two classes in your app
  1. 在此清单更改之前,首先在您的应用程序中添加这两个类

public final class AnalyticsTrackers {

公共最终类 AnalyticsTrackers {

public enum Target {APP,}
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;
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);
}

}

}

And Add this AnalyticsApplication.java

并添加这个 AnalyticsApplication.java

public class AnalyticsApplication extends MultiDexApplication

{

{

private Tracker mTracker;
private static AnalyticsApplication mInstance;

@Override
public void onCreate()
{
    super.onCreate();
    mInstance = this;
    AnalyticsTrackers.initialize(this);
    AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);
}

synchronized public Tracker getDefaultTracker()
{
    if (mTracker == null)
    {
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(AnalyticsApplication.this);

        mTracker = analytics.newTracker(R.xml.app_tracker);
    }
    return mTracker;
}

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

public void trackEvent(String category, String action, String label)
{
    Tracker t = getDefaultTracker();
    t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
}

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

public void trackScreenView(String screenName)
{
    Tracker t = getGoogleAnalyticsTracker();
    t.setScreenName(screenName);
    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()
        );
    }
}

}

}

  1. And last we can add code in your mainactivity.java class or you required classes Initialize Step1

    AnalyticsApplication application1;

    private Tracker mTracker;

    Step :2

    application1 = (AnalyticsApplication) getApplication();

    mTracker = application1.getDefaultTracker();

  1. 最后我们可以在您的 mainactivity.java 类或您需要的类中添加代码 Initialize Step1

    分析应用程序1;

    私人追踪器 mTracker;

    第2步

    application1 = (AnalyticsApplication) getApplication();

    mTracker = application1.getDefaultTracker();

if you run this code in google analytics showing screen name you mentioned in xml.

如果您在谷歌分析中运行此代码,显示您在 xml 中提到的屏幕名称。

Step :3 Add this code for track event

步骤 :3 为跟踪事件添加此代码

mTracker.send(new HitBuilders.EventBuilder()

                .setCategory("DashBoard ")

                    .setAction("View Bookings Pressed")

                    .build());

Step :4 Track exception behaviour code add in you catch block

步骤 :4 在 catch 块中添加跟踪异常行为代码

 catch (Exception e) {
         **   AnalyticsApplication.getInstance().trackException(e);**
            e.printStackTrace();
        }

Happy coding..

快乐编码..