androidandroid-fragmentsfragmentfragment-lifecycle

How to detect fragment is idle for some time in android


I want to check that no one has interacted with fragment UI for some time and on the bases of that I want to call a Function/Method inside fragment. Android Studio


Solution

  • You could use a Handler for this and call resetTimeout() when the user does something:

    
      val timeoutHandler = Handler(Looper.getMainLooper()) {
        onTimeout()
        true
      }
    
      fun clearTimeout() = timeoutHandler.removeMessages(0)
    
      fun resetTimeout() =
          clearTimeout().also {
            timeoutHandler.sendEmptyMessageDelayed(0, TIMEOUT_IN_MILLIS)
          }
    
    
      override fun onResume() {
        super.onResume()
        resetTimeout()
      }
    
      override fun onPause() {
        super.onPause()
        clearTimeout()
      }
    
      private fun onTimeout() {
        //we have timed out
      }