Thread.sleep() or Object.wait() on Android UI Thread

ID

java.android_wait_sleep_activity

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:400, android, concurrency, reliability

Description

Reports calls to Thread.sleep(…​) or Object.wait(…​) that occur inside methods of an Activity or Fragment subclass. These calls block the main (UI) thread and can cause an Application Not Responding (ANR) dialog after approximately five seconds, degrading the user experience and potentially causing the system to kill the process.

Rationale

The Android framework dispatches UI events (touch, draw, lifecycle callbacks) on the main thread. Any long-running or blocking operation — including Thread.sleep() and Object.wait() — prevents the framework from processing input, leading to ANR:

public class MyActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
      Thread.sleep(5000); // Blocks the UI thread -- ANR
    } catch (InterruptedException e) { }
  }
}

Methods named doInBackground (the classic AsyncTask background callback) are excluded because they execute on a worker thread, not the UI thread.

Remediation

Move blocking work to a background thread. Use AsyncTask.doInBackground(), HandlerThread, ExecutorService, Kotlin coroutines, or WorkManager for deferred tasks:

public class MyActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new Thread(() -> {
      try {
        Thread.sleep(5000); // OK: runs on a background thread
      } catch (InterruptedException e) { }
      runOnUiThread(() -> updateUi());
    }).start();
  }
}