简体   繁体   English

如何在Android应用中集成Google Analytics

[英]How to integrate Google Analytics in Android app

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. 您好我正在尝试集成Google Analytics,但我无法找到我的Google Analytics帐户中显示的任何分析数据。 I am using the link mention below:- 我正在使用下面提到的链接: -

developers.google.com link 1 developers.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. 但我无法获得结果,也无法获得正确的路径/方式或正确的详细教程,以了解如何在Android应用中集成Google Analytics。

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:- 我的Analytics Helper类如下: -

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. 提前致谢。

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. 您需要做的就是设置代码并添加Jar文件将Google Analytics Jar文件下载到您的Lib。 just wait for 24 to 48 hours. 等待24至48小时。 and it would show all the events and analytic for the App you had registered. 它会显示您已注册的应用程序的所有事件和分析。

Edited Answer:- 编辑答案: -

Once You had Created your Google Analytic account and Downloaded the Jar file, Add the Jar file in your lib folder of your Application 创建Google Analytic帐户并下载Jar文件后,在应用程序的lib文件夹中添加Jar文件

Google Analytic Implementation:- Google Analytic Implementation: -

Well For Analytic Part You Just need the analytic.xml file to be included in your values folder which is mentioned in the Question. 那么对于分析部分您只需要将analytic.xml文件包含在问题中提到的值文件夹中。

Then define private EasyTracker easyTracker = null; 然后定义private EasyTracker easyTracker = null; in your MainActivity . 在您的MainActivity中

And now in your onCreate(Bundle savedInstanceState) method just write the following lines of Code. 现在在你的onCreate(Bundle savedInstanceState)方法中只需编写以下代码行。 Well you can also write the following code for any Listners eg on any Button Click. 那么你也可以为任何Listners编写以下代码,例如任何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()方法中,只需编写以下代码,即可启动Activity的Tracking and Analytics会话。

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. 现在,您可以跟踪和分析您的应用程序和活动。

I have detailed the steps for integrating Google Analytics into an existing app here . 我详细介绍了在此处将Google Analytics集成到现有应用中的步骤。 When I publish a new app I always go back to these instructions which work well. 当我发布一个新的应用程序时,我总是回到这些说明运行良好。

  1. Fisrt we have to create google analytics track id Goolge analytics sign in and enable api and get track id Fisrt我们必须创建谷歌分析跟踪ID Goolge分析登录并启用api并获取跟踪ID

  2. After that put that track id in below .xml code 之后将该轨道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 analytics类名称示例“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 在此清单更改之前,首先在您的应用中添加这两个类

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 最后我们可以在mainactivity.java类中添加代码,或者您需要类Initialize Step1

    AnalyticsApplication application1; AnalyticsApplication application1;

    private Tracker mTracker; 私人追踪器mTracker;

    Step :2 第2步

    application1 = (AnalyticsApplication) getApplication(); application1 =(AnalyticsApplication)getApplication();

    mTracker = application1.getDefaultTracker(); 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为track事件添加此代码

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.. 快乐的编码..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将Google Analytics(分析)集成到我的Android应用中 - Can Not Integrate Google Analytics in my Android app 将Google Analytics(分析)“ v4”集成到Android应用中 - Integrate Google Analytics “v4” into an Android app 如何为我的通用应用程序集成Google Analytics(分析)? - how to integrate google analytics for my universal app? Google Analytics:如何集成到Android应用程序中? - Google Analytics: How to integrate into Android application? 无法在 android 应用程序中集成谷歌分析以使用归因功能 - Could not integrate google analytics in android app to use Attribution feature 如何在android中集成firebase分析? - how to integrate firebase analytics in android? 如何在我的 Android 应用程序中集成 Google 地图 - How to integrate Google maps in my Android App 如何将Google Realtime Playground与Android App集成? - How to integrate Google Realtime Playground with Android App? 如何在Android应用程序中集成G​​oogle Play新闻? - How to integrate google play news in android app? 如何在 Android 应用程序中集成 Google 地图 - How to Integrate Google Maps in Android App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM