Search code examples
androidgoogle-analyticsgoogle-analytics-firebase

How to manually end a session in Google analytics v4 for Android?


I've been searching online for a few days but I couldn't find it. It was available in v3 but the only code available for managing the session manually in v4 is for starting a new one only and rely on the session timeout for the ending.


Solution

  • The public Android v4 api doesn't have support for ending the session but you can accomplish the same with session control end parameter from Measurement Protocol. You can do that by adding sc=end to your Tracker:

    analytics = GoogleAnalytics.getInstance(getApplicationContext());
    
    // TODO: Remove this line before shipping
    analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
    
    tracker = analytics.newTracker(TRACKER_ID);
    Map<String, String> hit = new HitBuilders.ScreenViewBuilder().build();
    hit.put("&sc", "end");
    tracker.send(hit);
    

    Verify that the sc parameter is send out by look at your logcat for "Sending hit" line and make sure it has sc=end parameter. It should look something like this:

    V/GAV4﹕ Thread[GAThread,5,main]: Sending hit to store  PATH: https:  PARAMS: v=1,  ul=en-us,  t=screenview,  ht=1417708068636,  sr=800x1216,  a=1647515955,  an=Analytics Playground,  sc=end,  tid=UA-xxxxxxxx-1,  aid=com.example.analyticsplayground,  cid=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,  av=1.0,  _u=.nK-AL,