How to Prevent Timeout Timer from Starting During System Prompts in Android App

20 Views Asked by At

I'm working on implementing a timeout feature in an Android app that redirects the user to a login screen when they leave the app for a certain time. The timer is supposed to start during the app's pause state (onPause()) and cancel during the resume state (onResume()). However, I've encountered an issue where the timer starts counting even when a system prompt, dialog, or similar UI element is displayed, which is not the intended behavior.

Here's the relevant code snippet from my BaseActivity class that includes the timeout logic:

    class BaseActivity : AppCompatActivity() {
    companion object {
        const val TIMEOUT_VALUE = 15000L // Timeout after 15 seconds
    }

    override fun onResume() {
        super.onResume()
        // Cancel the timeout timer when the app resumes
        TimeoutManager.cancelTimer()
    }

    override fun onPause() {
        super.onPause()
        // Start the timeout timer when the app pauses
        TimeoutManager.startTimer(this) {
            redirectToLogin()
        }
    }

    private fun redirectToLogin() {
        val intent = Intent(this, LoginActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        startActivity(intent)
    }
}

object TimeoutManager {
    private var logoutJob: Job? = null
    private val activityScope = CoroutineScope(Dispatchers.Main)

    fun startTimer(activity: AppCompatActivity, redirectToLogin: () -> Unit) {
        cancelTimer()
        logoutJob = activityScope.launch {
            delay(BaseActivity.TIMEOUT_VALUE)
            activity.runOnUiThread { redirectToLogin() }
        }
    }

    fun cancelTimer() {
        logoutJob?.cancel()
    }
}

The issue occurs when system-level prompts or dialogs appear (for example, permission requests, alert dialogs, etc.). The app technically goes into pause state, triggering the onPause() method and thus starting the timeout timer. This leads to unintended logouts or redirects to the login screen even when the user is actively using the app.

I'm looking for a way to differentiate between the app being sent to the background by the user (e.g., pressing the home button or switching apps) and the app being paused due to internal dialogs or system prompts. Ideally, the timeout timer should only start in the former scenario.

Has anyone faced a similar issue or can provide insight into how to achieve this? Any suggestions or guidance would be greatly appreciated.

0

There are 0 best solutions below