What is ANR?
Application Not Responding
The main reasons for ANR:
The responsiveness of the application is monitored by the ActivityManager and WindowManager system services. When it is monitored that the main thread clicks in the Activity for more than 5 seconds and there is no response or there is no response in the broadcast UI thread for more than 10 seconds, it will cause ANR. Here are the specifics:
- The main thread is blocked by I/O operations (network IO is not allowed in the main thread since 4.0).
- There are time-consuming computations in the main thread.
The main reason for ANR: Which operations are in the main thread in Android?
- All lifecycle callbacks of Activity are executed on the main thread.
- Service is executed on the main thread by default.
- The onReceive callback of BroadcastReceiver is executed on the main thread.
- The handleMessage of the Handler of the looper of the child thread is not used, and post(Runnable) is executed on the main thread.
- Except for doInBackground, the callback of AsyncTask is executed on the main thread.
How to fix ANRs:
- Use Asynctask to handle time-consuming IO operations.
- Use Thread or HandlerThread to increase the priority.
- Use Handler to handle time-consuming tasks of worker threads.
- Try to avoid time-consuming code in the Activity's onCreate() and onResume() callbacks.