google analytics-NetworkOnMainThread发送异步任务时出现异常

iyr7buue  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(325)

我必须在我正在开发的应用程序中实现谷歌分析。我用的是安卓工作室。
我还不太确定我是否应该从每个活动中实现发送跟踪程序,或者是否只执行一次 Application class 够了,但那是另一回事。目前,谷歌分析是在美国实施的 Application class . 它试图连接到某个东西(尽管我已经设置了 dryRun ),失败,然后什么也不说,除非我导致我的应用程序崩溃。然后我得到 NetworkOnMainThreadException 尝试分派事件时出错。
它试图在什么地方发送事件 dryRun ,导致 NetworkOnMainThreadException 不少于?它不应该在运行时把所有东西都发送到logcat吗 dryRun ? 我该怎么处理这两个问题呢 dryRun 而不是?
一开始我试着像那样实现它,没有额外的代码 AsyncTask 同学们,假设我会把所有东西都扔给logcat,但是当我拿到 NetworkOnMainThreadException 第一次出错,我实现了 AsyncTask 班级。
日志:

01-15 13:06:21.835    1787-1800/com.example.app W/GAV4﹕ Thread[GAThread,5,main]: Service unavailable (code=1), will retry.
01-15 13:06:26.847    1787-1808/com.example.app W/GAV4﹕ Thread[Service Reconnect,5,main]: Service unavailable (code=1), using local store.
01-15 13:07:12.695    1787-1787/com.example.app E/GAV4﹕ Thread[main,5,main]: Error dispatching all events on exit, giving up: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:926)
        at org.apache.http.impl.SocketHttpClientConnection.shutdown(SocketHttpClientConnection.java:183)
        at org.apache.http.impl.conn.DefaultClientConnection.shutdown(DefaultClientConnection.java:150)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.shutdown(AbstractPooledConnAdapter.java:169)
        at org.apache.http.impl.conn.AbstractClientConnAdapter.abortConnection(AbstractClientConnAdapter.java:378)
        at org.apache.http.impl.client.DefaultRequestDirector.abortConnection(DefaultRequestDirector.java:1031)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:530)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
        at com.google.android.gms.analytics.h.a(Unknown Source)
        at com.google.android.gms.analytics.h.a(Unknown Source)
        at com.google.android.gms.analytics.ag.dispatch(Unknown Source)
        at com.google.android.gms.analytics.w.eD(Unknown Source)
        at com.google.android.gms.analytics.w.dispatch(Unknown Source)
        at com.google.android.gms.analytics.x$b.run(Unknown Source)
        at com.google.android.gms.analytics.x.dY(Unknown Source)
        at com.google.android.gms.analytics.GoogleAnalytics.dY(Unknown Source)
        at com.google.android.gms.analytics.ExceptionReporter.uncaughtException(Unknown Source)
        at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
        at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
        at dalvik.system.NativeStart.main(Native Method)

应用类别(相关部分):

public class App extends Application {

private static App context = null;

private static final String PROPERTY_ID = "UA-xxxxxxxx-1";

private GoogleAnalytics analytics;

private Tracker t;

public void onCreate() {
    super.onCreate();
    if (context == null)
        context = (App) getApplicationContext();
    try {
        analytics = GoogleAnalytics.getInstance(context);
        t = analytics.newTracker(R.xml.app_tracker);
        new SendTrackerInBg(t);
    }
    catch (Exception e) {e.printStackTrace();}

}

发送跟踪BG:

public class SendTrackerInBg extends AsyncTask<Tracker, Void, Integer> {

    SendTrackerInBg(Tracker t)
    {
        this.execute(t);
    }

    @Override
    protected Integer doInBackground(Tracker... trackers) {
        try {
            trackers[0].send(new HitBuilders.AppViewBuilder().build());
            return 0;
        }
        catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}

app\ u tracker.xml(相关部分):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="ga_sessionTimeout">300</integer>

    <!-- Enable automatic Activity measurement -->
    <bool name="ga_autoActivityTracking">true</bool>

    <!-- The screen names that will appear in reports -->
    <screenName name="com.example.app.App">
        Application
    </screenName>
    <string name="ga_sampleFrequency">300.0</string>
    <string name="ga_trackingId">UA-xxxxxxxx-1</string>
    <bool name="ga_reportUncaughtExceptions">true</bool>
</resources>

分析\u全局\u config.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="ga_dryRun">true</bool>
    <string name="ga_logLevel">verbose</string>
</resources>

舱单(相关部分):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app"
android:versionCode="00"
android:versionName="0.00" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<permission
    android:name="com.example.app.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.app.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<meta-data
    android:name="com.google.android.gms.analytics.globalConfigResource"
    android:resource="@xml/analytics_global_config" />

<application
    android:name=".App"
    android:allowBackup="true"
    android:hardwareAccelerated="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

upd:多亏了@bart hofma,我意识到我的应用程序崩溃可能会让人困惑。当ga试图调度事件时,我的应用程序不会崩溃。相反,ga只在我的应用程序崩溃时才尝试发送事件,否则它将保持沉默。我故意让我的应用程序崩溃,看看ga会怎么说。我有一个定制的视频播放器,可以在真实设备上正常工作,但在虚拟机上崩溃,所以当我想让我的应用程序崩溃时,我只需转到虚拟机上的播放器活动。

x6yk4ghg

x6yk4ghg1#

我浪费了一天时间搜索这个解决方案(我有相同的线程转储行),并发布了它与谷歌分析没有直接关系。根本原因是下一行:adview.destroy();其中adview==null。似乎谷歌分析试图发送这个例外,并崩溃了自己。我是通过禁用谷歌分析找到的。

ezykj2lf

ezykj2lf2#

你必须从线程调用谷歌分析。我在这里分享我的工作代码。
将此代码放入类中(mbgoogleanalyticsmanager.java)

import android.content.Context;
 import com.google.android.gms.analytics.GoogleAnalytics;
 import com.google.android.gms.analytics.HitBuilders;
 import com.google.android.gms.analytics.Tracker;

public class MBGoogleAnalyticsManager  
{
    private static final String TAG = "MBGoogleAnalyticsManager";
    private static MBGoogleAnalyticsManager instance = null;
    public String PROPERTY_ID = "UA-28454545-2";

    private Context context;
    private Tracker dataTracker;

    public static MBGoogleAnalyticsManager getInstance(Context c) 
        {
            if(instance == null) 
                {
                    System.out.println("MBGoogleAnalyticsManager new instance is created");
                    instance = new MBGoogleAnalyticsManager(c);
                }
            else
                {
                    System.out.println("MBGoogleAnalyticsManager instance is already avaiable");
                }
            return instance;
        }

    private MBGoogleAnalyticsManager(Context c)     
        {
            //super(c);
            context = c;
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(context);   
            dataTracker = analytics.newTracker(PROPERTY_ID);
        }

      //==============================================================================
     //========================== Send a screen view =================================
    //================================================================================
    public synchronized void sendGoogleAnalyticsSreenView(String screenName)
        {               
            dataTracker.setScreenName(screenName);    // Set screen name.
            //dataTracker.setAppName("MovieBuddy");  // We can send the application name [String](Optional)
            //dataTracker.setAppVersion("2.2");     // We can send the application version [String](Optional)
            //dataTracker.setLanguage("Eng");      // We can send the language [String](Optional)
            //dataTracker.setSessionTimeout(300); // We can set the time for the session time out [Long](Optional)

            dataTracker.send(new HitBuilders.AppViewBuilder()    
                                            //.setNewSession()   // If want to start a new session (Optional)
                                            .build());
            System.out.println("Screen: "+screenName);
        }

      //==============================================================================
     //========================== Send A Click Event Hit =============================
    //================================================================================
    public synchronized void sendGoogleAnalyticsHitEvents(String screenName,String category,String action,String label)
        {       
            dataTracker.setScreenName(screenName);
            dataTracker.send(new HitBuilders.EventBuilder()         
                                            .setCategory(category) // Set the category of the event [String]
                                            .setAction(action)    // Set the action has taken for the event [String]
                                            .setLabel(label)     // Set the label of for the event [String]
                                            .build());
            System.out.println("Hit Label: "+label);
        }

      //==============================================================================
     //========================== Send A Exception Event =============================
    //================================================================================

    public synchronized void sendGoogleAnalyticsException(String screenName,String ExceptionMethodName,String ExceptionLocation,boolean ExceptionFatal)
        {   
            dataTracker.setScreenName(screenName);
            dataTracker.send(new HitBuilders.ExceptionBuilder()                                         
                                            .setDescription(ExceptionMethodName + ":" + ExceptionLocation) // Send the exception details [String]
                                                                                                          //(Never send the e.message, as it contains personal info)
                                            .setFatal(ExceptionFatal)                                    // Send true or false if fatal exception error [boolean]
                                            .build());
        }

      //==============================================================================
     //================ Send A Social Event Interaction With target ==================
    //================================================================================
    public synchronized void sendGoogleAnalyticsSocialInteractionWithTarget(String screenName,String SocialNetworkName,String SocialAction,String SocialTarget)
        {       
            dataTracker.setScreenName(screenName);
            dataTracker.send(new HitBuilders.SocialBuilder()                 
                                            .setNetwork(SocialNetworkName)  // Set the Social Network Name [String]
                                            .setAction(SocialAction)       // Set the action [String]
                                            .setTarget(SocialTarget)      // Set the target [String](Not a mandatory field)
                                            .build());
            System.out.println("Target: "+SocialTarget);
        }

      //==============================================================================
     //============== Send A Social Event Interaction Without target =================
    //================================================================================

    public synchronized void sendGoogleAnalyticsSocialInteraction(String SocialNetworkName,String SocialAction)
        {       
            dataTracker.send(new HitBuilders.SocialBuilder()
                                            .setNetwork(SocialNetworkName)// Set the Social Network Name [String]
                                            .setAction(SocialAction)     // Set the action [String]
                                            .build());
        }
}

现在您必须调用这个类示例、方法,并提供调用类所需的数据,如下所示:

private void sendScreenView(final String screenName)
    {   
        new Thread(new Runnable() 
            {
                @Override
                public void run() 
                    {                           
                        analyticsManager = MBGoogleAnalyticsManager.getInstance(getApplicationContext());
                        analyticsManager.sendGoogleAnalyticsSreenView(screenName);
                    }
            }).start();
    }

并调用此方法:
sendscreenview(“家庭活动”);
希望对你有帮助。

相关问题