Reprint please indicate the source: Wang 亟亟 's way of Daniel
Crashes and non-responsiveness are often encountered in our development process and are very unwanted problems like this:
Crash
Or is that so?
Normally, when our main thread is blocked, there is an unresponsive situation, and some exceptions appear to be handled and a system crash occurs.
Here we say the ANR:
Full Name:Application Not responding
When does it usually appear?
-The main thread ("Event processing Thread"/"UI thread") did not respond to input events within 5 seconds
-broadcastreceiver did not complete the return within 10 seconds
-The main thread is blocked by IO operations (Network IO is not allowed in the main thread after 4.0).
-time-consuming calculations in the main thread
-incorrect operations in the main thread, such as thread.wait or thread.sleep, etc.
How will the system usually inform the user?
The system will pop up a anr dialog box, the user can choose to continue to wait or stop the current program.
How to avoid it?
-Use Asynctask to process time-consuming IO operations.
Call Process.setthreadpriority (Process.thread_priority_background) to set the priority when using THREAD or handlerthread, or it will still degrade the program response. Because the default thread has the same priority as the primary thread.
-use handler to process worker thread results instead of blocking the main thread with thread.wait () or Thread.Sleep ().
Avoid time-consuming code in-activity's OnCreate and Onresume callbacks
The OnReceive code in-broadcastreceiver also minimizes time-consuming, and it is recommended to use intentservice processing.
Usually 100 to 200 milliseconds will make people aware of the slow process, in order to improve the response, you can use the following several methods
-If the program is processing user input in the background, it is recommended to let the user know the progress, such as using the ProgressBar control.
-You can choose to add a welcome screen when the program starts, avoiding the user's awareness of stalling.
-Use Systrace and TraceView to identify issues that affect the response.
Android ANR Trivia