Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android ActivityLifecycleCallbacks that will only call back for a specific activity (not all activities)
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import java.util.Locale;
public class UniqueActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
private final String activityName;
private final Application.ActivityLifecycleCallbacks lifecycleCallbacks;
public static UniqueActivityLifecycleCallbacks newInstance(Activity activity, Application.ActivityLifecycleCallbacks lifecycleCallbacks) {
return new UniqueActivityLifecycleCallbacks(getActivityName(activity), lifecycleCallbacks);
}
UniqueActivityLifecycleCallbacks(String activityName, Application.ActivityLifecycleCallbacks lifecycleCallbacks) {
this.activityName = activityName;
this.lifecycleCallbacks = lifecycleCallbacks;
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (theseAreTheDroidsWeAreLookingFor(activity)) {
lifecycleCallbacks.onActivityCreated(activity, savedInstanceState);
}
}
@Override
public void onActivityStarted(Activity activity) {
if (theseAreTheDroidsWeAreLookingFor(activity)) {
lifecycleCallbacks.onActivityStarted(activity);
}
}
@Override
public void onActivityResumed(Activity activity) {
if (theseAreTheDroidsWeAreLookingFor(activity)) {
lifecycleCallbacks.onActivityResumed(activity);
}
}
@Override
public void onActivityPaused(Activity activity) {
if (theseAreTheDroidsWeAreLookingFor(activity)) {
lifecycleCallbacks.onActivityPaused(activity);
}
}
@Override
public void onActivityStopped(Activity activity) {
if (theseAreTheDroidsWeAreLookingFor(activity)) {
lifecycleCallbacks.onActivityStopped(activity);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (theseAreTheDroidsWeAreLookingFor(activity)) {
lifecycleCallbacks.onActivitySaveInstanceState(activity, outState);
}
}
@Override
public void onActivityDestroyed(Activity activity) {
if (theseAreTheDroidsWeAreLookingFor(activity)) {
lifecycleCallbacks.onActivityDestroyed(activity);
}
}
private boolean theseAreTheDroidsWeAreLookingFor(Activity activity) {
String a = activityName.toLowerCase(Locale.UK);
String b = getActivityName(activity).toLowerCase(Locale.UK);
return a.equals(b);
}
private static String getActivityName(Activity activity) {
return activity.getClass().getSimpleName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment