Reputation: 679
I've implemented something similar for iOS using a quick swizzle of viewDidAppear to allow my company to track flow around the app in our own internal systems.
Now, ideally I'd like to avoid having to implement appear & disappear tracking in every activity for our internal use, so was hoping someone could shed some light into how the GA library achieves this.
I had a good google around and couldn't find any kind of internal event that's posted when an activity comes into the foreground so am at a bit of a loss at the moment.
Cheers!
Upvotes: 2
Views: 603
Reputation: 1499
You can use ActivityLifecycleCallback. Example below:
public class MordorApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleLogger());
}
}
public class ActivityLifecycleLogger implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
createActivityStateLog(activity, "created");
}
@Override
public void onActivityStarted(Activity activity) {
createActivityStateLog(activity, "started");
}
@Override
public void onActivityResumed(Activity activity) {
createActivityStateLog(activity, "resumed");
}
@Override
public void onActivityPaused(Activity activity) {
createActivityStateLog(activity, "paused");
}
@Override
public void onActivityStopped(Activity activity) {
createActivityStateLog(activity, "stopped");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
createActivityStateLog(activity, "savingStateInstance");
}
@Override
public void onActivityDestroyed(Activity activity) {
createActivityStateLog(activity, "destroyed");
}
private void createActivityStateLog(Activity activity, String state) {
String log = String.format("Activity %s - %s", activity.getClass().getName(), state);
LOG.debug(log);
}
private static final Logger LOG = LoggerFactory.getLogger(ActivityLifecycleLogger.class);
}
Upvotes: 3
Reputation: 1459
Google Analytics has automatic Activity tracking feature.
See
https://developers.google.com/analytics/devguides/collection/android/v4/?hl=en#analytics-xml
or do John's answer :)
You can create delegate class (suppose GaUtils
) then call that on resume/pause. Just one line, don't you?
@Override
protected void onPause() {
super.onPause();
GaUtils.onPause(screenName); // track pause
}
Upvotes: 1
Reputation: 752
I know the following is not a direct answer to your question but why not applying a basic OOP principle? Inheritance.
import android.app.Activity;
public class BaseActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
// hit when activity appears. Tell Appserver!
}
@Override
protected void onPause() {
super.onPause();
// hit when activity hides. Tell Appserver!
}
}
and then have your other Acivities extend this instead of android.app.Activity?
Upvotes: 3