Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ActivityLifecycleListener
import android.app.Activity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import java.lang.ref.WeakReference;
import java.util.function.Consumer;
public class ActivityLifecycleListener implements LifecycleObserver {
private int resumeCount = 0;
private WeakReference<Activity> activityReference;
private Consumer<Activity> onMoveToForeground;
private Consumer<Activity> onMoveToBackground;
public void setOnMoveToForeground(Consumer<Activity> onMoveToForeground) {
this.onMoveToForeground = onMoveToForeground;
}
public void setOnMoveToBackground(Consumer<Activity> onMoveToBackground) {
this.onMoveToBackground = onMoveToBackground;
}
public ActivityLifecycleListener(Activity activity) {
this.activityReference = new WeakReference<>(activity);
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onMoveToForeground() { // app moved to foreground
resumeCount++;
if(resumeCount == 1) return;
if(onMoveToForeground != null) onMoveToForeground.accept(activityReference.get());
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onMoveToBackground() { // app moved to background
if(onMoveToBackground != null) onMoveToBackground.accept(activityReference.get());
}
}
/*
ActivityLifecycleListener activityLifecycleListener = new ActivityLifecycleListener(this);
activityLifecycleListener.setOnMoveToBackground(activity -> {
Toast.makeText(activity, "onMoveToBackground", Toast.LENGTH_SHORT).show();
});
activityLifecycleListener.setOnMoveToForeground(activity -> {
Toast.makeText(activity, "onMoveToForeground", Toast.LENGTH_SHORT).show();
});
ProcessLifecycleOwner
.get()
.getLifecycle()
.addObserver(activityLifecycleListener);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment