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?
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
2
Answers
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:
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) { ... }
.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):