Android : How to detect App foreground/background
วันนี้เรามีอีกวิธีในการตรวจสอบว่าแอปฯของเราอยู่ในสถานะทำงานอยู่ (foreground) หรือถูกปิดหรือย่อให้อยู่เบื้องหลัง (Background) โดยวิธีนี้เราจะเรียกใช้ Lifecycle Observer ที่มากับ androidx (androidx.lifecycle.OnLifecycleEvent) ตรวจจับการทำงานของ Event ของแอปฯ
การเรียกใช้เราประกาศครั้งเดียวตอนเปิดแอปฯ แล้วตัว lifecycle จะคอยจับ event ให้เรา ดังนี้
public class MainApp extends AppCompatActivity implements LifecycleObserver { ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... // declare lifecycle ProcessLifecycleOwner.get().getLifecycle().addObserver(this); ... } @OnLifecycleEvent(Lifecycle.Event.ON_START) public void onMoveToForeground() { // app moved to foreground .... Do Something when App on Foreground .... } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onMoveToBackground() { // app moved to background .... Do Something when App on Foreground .... } }
ในตัวอย่างดังจับเฉพาะ ON_START, ON_STOP แต่ยังมี event อื่นให้เรียกใช้ อีกเช่น ON_ANY, ON_CREATE, ON_DESTROY, ON_PAUSE, ON_RESUME การเรียกใช้ก็เรียกใช้เหมือนตัวอย่างข้างต้น สมมติเราจะดังจับทุก events เราใช้ ON_ANY
@OnLifecycleEvent(Lifecycle.Event.ON_ANY) public void onAnyAction() { .... Do Something when detect lifecycle event.... }