Android Wait Sleep Activity

ID

kotlin.android_wait_sleep_activity

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

CWE:400, android, concurrency, reliability

Description

Reports calls to Thread.sleep(…​) or wait(…​) that occur inside methods of an Activity or Fragment subclass. These calls block the UI thread and may cause an Application Not Responding (ANR) dialog.

Rationale

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Thread.sleep(1000)                 // FLAW — blocks UI thread
    }

    override fun doInBackground(vararg params: Any?): Any? {
        Thread.sleep(5000)                  // OK — background thread
        return null
    }
}

Blocking the main thread for more than a few hundred milliseconds prevents the system from processing input events, dispatching draw callbacks, and posting frames. The user sees an unresponsive UI and Android may show the ANR dialog.

Remediation

  • Replace the blocking call with a coroutine delay(…​) inside lifecycleScope.launch { …​ }.

  • For one-shot work, dispatch to a background executor (Dispatchers.IO) and post the result back.

  • If the call truly must block, move it into a WorkManager worker, an IntentService, or a background thread the activity owns.