Google Analytics - NetworkOnMainThreadException on send in AsyncTask

前端 未结 2 1529
故里飘歌
故里飘歌 2020-12-10 21:29

I have to implement Google Analytics in the app I\'m working on. I\'m using Android Studio.

I\'m not quite sure yet if I should implement sending tracker from every

2条回答
  •  时光说笑
    2020-12-10 22:12

    You must call the google analytics from thread. Here i'm sharing the code what i'm working with.

    Put this code inside a class(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());
            }
    } 
    

    Now you have to call this class instance,method and provide the required data from you calling class like this:

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

    And Call this method:

    sendScreenView("Home Activity");

    Hope you will find it helpful.

提交回复
热议问题