implementation
'androidx.lifecycle:lifecycle-process:2.2.0'
public
class
ForegroundChecker
implements
LifecycleObserver {
private
boolean
isInForeground =
false
;
private
ForegroundChecker() {
}
@OnLifecycleEvent
(Lifecycle.Event.ON_STOP)
public
void
onRunInBackground() {
isInForeground =
false
;
}
@OnLifecycleEvent
(Lifecycle.Event.ON_START)
public
void
onRunInForeground() {
isInForeground =
true
;
}
public
boolean
isInForeground() {
return
isInForeground;
}
public
static
ForegroundChecker getInstance() {
return
Singleton.INSTANCE;
}
private
static
class
Singleton {
private
static
ForegroundChecker INSTANCE =
new
ForegroundChecker();
}
}
public
class
MyApp
extends
Application {
@Override
public
void
onCreate() {
super
.onCreate();
initLifecycleObserver();
}
private
void
initLifecycleObserver() {
ProcessLifecycleOwner.get().getLifecycle().addObserver(ForegroundChecker.getInstance());
}
}
public
class
MainActivity
extends
AppCompatActivity {
private
ForegroundChecker foregroundChecker;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
foregroundChecker = ForegroundChecker.getInstance();
}
}