ActivityLifecycleCallbacks
Application.registerLifecycleCallbacks()
onStart()
onStop()
public class PerfLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { private static final PerfLifecycleCallbacks instance = new PerfLifecycleCallbacks(); private PerfLifecycleCallbacks() {} public static PerfLifecycleCallbacks getInstance() { return instance; } }
private final HashMap<Activity, Trace> traces = new HashMap<>(); @Override public void onActivityStarted(Activity activity) { String name = activity.getClass().getSimpleName(); Trace trace = FirebasePerformance.startTrace(name); traces.put(activity, trace); } @Override public void onActivityStopped(Activity activity) { Trace trace = traces.remove(activity); trace.stop(); } // ...empty implementations of other lifecycle methods...
@Nullable public Trace getTrace(Activity activity) { return traces.get(activity); }
public class PerfInitContentProvider extends ContentProvider { @Override public boolean onCreate() { context = getContext(); if (context != null) { Application app = (Application) context.getApplicationContext(); app.registerActivityLifecycleCallbacks( PerfLifecycleCallbacks.getInstance()); } } }
getTrace()
private Trace trace; @Override protected void onCreate(Bundle savedInstanceState) { trace = PerfLifecycleCallbacks.getInstance().getTrace(this); // use the trace to tally counters... }