1

StrictMode is designed to be used in development and is disabled by default without developer mode, so I'm wondering if there is a way to detect ANR condition ahead, in order to intervene properly before OS ends in ANR timeout that under a specific situation is long and certainly will conclude with an annoying and generic message "App doesn't respond" after a waste of time for nothing.

AndreaF
  • 11,975
  • 27
  • 102
  • 168
  • This feels like a [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) as any condition which could cause ANR should be managed before getting to that point. Also see: [Listen and respond to ANR?](https://stackoverflow.com/q/8780831/295004) – Morrison Chang Feb 20 '22 at 03:08

2 Answers2

1

No. In fact its mathematically provable you can't. What you're asking is the equivalent of the Halting Problem- a mathematical question of whether or not its possible to write a program that can detect if another program will ever end or not. Alan Turing proved that it's impossible for the general case back in the 30s.

Strict mode does something much smaller than that. It defines conditions in order to do certain things (like you can't be on the main thread to make a socket call) and checks those conditions before it does those things. You could definitely increase the amount of things strict mode can catch, but you can never make it catch all ANRs.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
-1

To prevent ANR from happening, you should avoid doing any disk IO or network operations in the UI Thread. Same applies for any other long running operation (think about for loop or while conditions) that does not make any real UI changes.

UI thread is only for UI events. The other tasks can be safely done in a separate background thread. There are lots of libraries that already do that for you. For example Volley will perform network requests on a background thread and post the results to your UI. Glide is an image loading and caching library that does the network calls and post-processing of images on a background thread. It delivers the result to your UI, with minimal delay.

So, to answer your question: You can't detect ahead an ANR. But there a lots of things you can do to prevent them from happening in the first place.

Ezequiel Adrian
  • 726
  • 1
  • 11
  • 29