Skip to content

Instantly share code, notes, and snippets.

@yunusemredilber
Created October 5, 2020 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yunusemredilber/44e6d5cc7fe286b1061602b3e5aa35be to your computer and use it in GitHub Desktop.
Save yunusemredilber/44e6d5cc7fe286b1061602b3e5aa35be to your computer and use it in GitHub Desktop.
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