getDefaultTracker() from a class that extends InputMethodService?

前端 未结 1 489
小鲜肉
小鲜肉 2021-01-18 15:47

I have a keyboard app for Android that I\'m developing, and it outputs simple symbols rather than language, so that said, I would love to be able to track user activity sinc

相关标签:
1条回答
  • 2021-01-18 16:14

    It's not necessary that you have an Application to use the Google Analytics' Android SDK.

    The example adds the helper method getDefaultTracker inside the Application class to centralize and ease the access to the default tracker. In most cases this would be the best possible solution, for this reason the example recommends this approach. But there are some exceptions where this solution is not feasible, like in the InputMethodService.

    As you can see in the documentation the parameter of the method getInstance is a Context:

    public static GoogleAnalytics getInstance (Context context)

    Gets the instance of the GoogleAnalytics, creating it when necessary. It is safe to call this method from any thread

    For this reason you can use the very same getDefaultTracker method directly inside your InputMethodService. For example:

    public class InputMethodServiceSample extends InputMethodService {
    
        private Tracker mTracker;
    
        /**
        * Gets the default {@link Tracker} for this {@link Application}.
        * @return tracker
        */
        synchronized public Tracker getDefaultTracker() {
            if (mTracker == null) {
                GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
                // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
                mTracker = analytics.newTracker(R.xml.global_tracker);
            }
            return mTracker;
        }
    }
    

    then you can use the methods getDefaultTracker in every method of your service.

    0 讨论(0)
提交回复
热议问题