Created
October 5, 2020 14:45
-
-
Save yunusemredilber/44e6d5cc7fe286b1061602b3e5aa35be to your computer and use it in GitHub Desktop.
ActivityLifecycleListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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