Integrate Google Analytics “v4” into an Android app

 ̄綄美尐妖づ 提交于 2019-12-02 07:58:58

As described in your link, the GA-related code should be placed inside the Application class instead of the Activity.

Create a class extends Application like this:

public class MyApplication extends Application{
    //the tracker related code should be place here (the enum, getTracker, mTrackers)
}

then in your AndroidManifest.xml, under the application tag, replace the android:name with the above MyApplication class.

The tracker code should be placed in the Activity.oncreate method such as

public class MainActivity extends Activity {
.
.
.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// Get tracker.
    Tracker t = ((AnalyticsSampleApp) getApplication()).getTracker(
        TrackerName.APP_TRACKER);

    // Set screen name.
    // Where path is a String representing the screen name.
    t.setScreenName(path);

    // Send a screen view.
    t.send(new HitBuilders.AppViewBuilder().build());
}
.
.
.
}

Today i faced same issue and got your post, but no one has pointed to right direction.

But i found solution and got the google analytics code working.

Please do follow:

1st - Move tracking code to your fragment class in public void onCreate(Bundle savedInstanceState) method (this has been changed in V4)
Reason: Because the lifetime of fragments is not as straightforward as that of Activities. Android does not provide callbacks for fragment lifecycle.

2nd - Step 2 from v4 implementation doc the Initialize Trackers code should be written into the Application class. Important for Application Class refer application tag and property as android:name="com.brodev.socialapp.entity.User" from AndroidManifest.xml

Please mark answer UP if this helps. So it will help others.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!