Search code examples
androidandroid-intentusage-statistics

How can I track my android app users detailed statistics?


UsageStatsManager seems to provide general statistics for all apps on your device, however, I am interested in tracking my own apps user detailed statistics. For instance, how many seconds does a certain activity stay opened? how many times is it opened? how many times a button is clicked?

Google provides a nice way to report on your app statistics & reports here but this not what I am looking for!

What I am looking for is either an app that plugs in to my intents (which I doubt is viable) OR another class/package that provides this functionality given that I plug it in my code (more like a usage calculator that attaches to my intent)


Solution

  • Integrate google analytics. So easy:

    Add this code to MyApplication class (Consts is my private class where is defined property id):

    import com.google.android.gms.analytics.GoogleAnalytics;
    import com.google.android.gms.analytics.Tracker;
    
       public class MyApplication extends Application {     
            private static Context context; 
            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 synchronized Tracker getTracker(TrackerName trackerId) {
              if (!mTrackers.containsKey(trackerId)) {
    
                GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
                Tracker t = analytics.newTracker(Consts.ANALYTICS_PROPERTY_ID);
                mTrackers.put(trackerId, t);
    
              }
              return mTrackers.get(trackerId);
            }
    
            public void onCreate(){
                super.onCreate();
                MyApplication.context = getApplicationContext();  
            }
    
            public static Context getAppContext() {
                return MyApplication.context;
            }
    
        }
    

    And this code add to your fragment file:

    import com.google.android.gms.analytics.HitBuilders;
    import com.google.android.gms.analytics.Tracker;
    
    
    Tracker t = ((MyApplication) getActivity().getApplication()).getTracker(TrackerName.APP_TRACKER);       
    t.setScreenName("My screen name");
    t.send(new HitBuilders.AppViewBuilder().build());