앱이 포그라운드에 있는지 백그라운드에 있는지 체크하는 클래스를 만들어 봤습니다. 급조한거라 동작은 잘 하는 것 같은데 코드 수정 및 테스트가 더 필요할 듯 합니다.
// app build.gradle에 dependency 추가
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();
//foregroundChecker.isInForeground() ? "Foreground" : "Background"
}
}
참고로, 전 androidx만 쓰기 때문에 Androidx를 쓰지 않으시면 마이그레이션 하시길 권장드리며, 굳이 support library를 쓰셔야 한다면 https://developer.android.com/reference/android/arch/lifecycle/ProcessLifecycleOwner 에서 확인해 보시길 바랍니다. 참고로 ForegroundChecker는 inner static singleton을 사용하는 Singleton 클래스입니다.
그리고 Service보다는 WorkManager를 권장하는 것 같습니다. 관심이 있으시면 이것도 살펴보시면 더 안정적인 앱을 만드시는게 도움이 될 듯 합니다.
https://developer.android.com/topic/libraries/architecture/workmanager