Created
July 10, 2017 06:15
-
-
Save kaciula/f4283839de750444632bc6ffb40f13a5 to your computer and use it in GitHub Desktop.
Foreground detector
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
public class ForegroundDetector implements Application.ActivityLifecycleCallbacks { | |
private int refs; | |
private boolean isChangingOrientation; | |
private PublishSubject<ForegroundState> subject = PublishSubject.create(); | |
public ForegroundDetector(Application app) { | |
app.registerActivityLifecycleCallbacks(this); | |
} | |
@Override | |
public void onActivityCreated(Activity activity, Bundle savedInstanceState) { | |
} | |
@Override | |
public void onActivityStarted(Activity activity) { | |
Timber.d("activity started"); | |
if (++refs == 1 && !isChangingOrientation) { | |
Timber.i("activity app became foreground"); | |
subject.onNext(ForegroundState.APP_BECAME_FOREGROUND); | |
} | |
} | |
@Override | |
public void onActivityResumed(Activity activity) { | |
Timber.d("activity resumed"); | |
subject.onNext(ForegroundState.ACTIVITY_RESUMED); | |
} | |
@Override | |
public void onActivityPaused(Activity activity) { | |
Timber.d("activity paused"); | |
subject.onNext(ForegroundState.ACTIVITY_PAUSED); | |
} | |
@Override | |
public void onActivityStopped(Activity activity) { | |
Timber.d("activity stopped"); | |
isChangingOrientation = activity.isChangingConfigurations(); | |
if (--refs == 0 && !isChangingOrientation) { | |
Timber.i("activity app became background"); | |
subject.onNext(ForegroundState.APP_BECAME_BACKGROUND); | |
} | |
} | |
@Override | |
public void onActivitySaveInstanceState(Activity activity, Bundle outState) { | |
} | |
@Override | |
public void onActivityDestroyed(Activity activity) { | |
} | |
public boolean isForeground() { | |
return refs > 0; | |
} | |
public boolean isBackground() { | |
return refs == 0 && !isChangingOrientation; | |
} | |
public Observable<ForegroundState> refresher() { | |
return subject; | |
} | |
public enum ForegroundState { | |
APP_BECAME_FOREGROUND, APP_BECAME_BACKGROUND, ACTIVITY_RESUMED, | |
ACTIVITY_PAUSED | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment