preface

Show yourself a series

To achieve this, when our App is switched to the background or the user clicks the HOME button and returns to our App, a global popup window will pop up or jump to the desired interface. The key code has been uploaded to Github, please help yourself if necessary. The code mainly refers to “Android APP Switch Monitor”

The main implementation

By making Application registration ActivityLifecycleCallbacks and onActivityResumed onActivityPaused and determine what is the current Activity which a life cycle is completed.

Key code:

  • Description:CHECK_DELAYIt’s for normalActivityJump when firstActivitytheonActivityPausedIn thecheckBefore this Handler is executed, a second Handler is executedActivityinonActivityResumedIt’s removed. This will trigger the listener only when you switch apps or hit the HOME button.
  • CHECK_DELAYThe value of is subject to change depending on the specific development situation.
private val listeners = CopyOnWriteArrayList<Listener>() private var check: Runnable? = null var isForeground = false var isPaused = true companion object { const val CHECK_DELAY = 600L } private val handler = Handler(Looper.myLooper()!!) Override fun onActivityResumed(activity: activity) {isPaused = false isForeground isForeground = true if (check ! = null) { handler.removeCallbacks(check!!) } if (wasBackground) { try { listeners.last().onBecameBackground() } catch (e: Exception) { Log.e(TAG, "onBecameForeground: ", e) } } } override fun onActivityPaused(activity: Activity) { isPaused = true if (check ! = null) { handler.removeCallbacks(check!!) } check = Runnable { if (isForeground && isPaused) { isForeground = false try { listeners.last().onBecameBackground() } catch (e: Exception) { Log.e(TAG, "onBecameBackground: ", e) } } } handler.postDelayed(check!! , CHECK_DELAY) }Copy the code