skip to Main Content

I need to test some of my code but I need to emulate some high pressure on the main thread so the app goes ANR. And I will have to handle that. How can I achieve it with code?

2

Answers


  1. If you just want an ANR response from the Android system it suffices to block the main thread. That can easily be achieved by something like this:

    runBlocking { delay(1.minutes) }
    

    Adjust the delay as needed.

    If you want to block the main thread from another thread you need to wrap this with withContext(Dispatchers.Main) { ... }.

    Login or Signup to reply.
  2. As other answers suggest, simply blocking the main thread is not enough, there has to be a user interaction while the main thread is hanging (see my slides here).

    Besides, the most reliable way I’ve found to trigger an ANR is to have an artificial deadlock (the user interaction requirement from above still stands true):

    final Object mutex = new Object();
    new Thread(new Runnable() {
      @Override
      public void run() {
        synchronized (mutex) {
          while (true) {
            try {
              Thread.sleep(10000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }).start();
    
    new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
        synchronized (mutex) {
          // Shouldn't happen
          throw new IllegalStateException();
        }
      }
    }, 1000);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search