Android ANR exception and how to fix it

Source: Internet
Author: User

Today interview encountered this problem, just at first did not see the meaning of the ANR abbreviation, and then asked the interviewer originally this means:

Anrs ("Application Not Responding"), meaning "app is not responding".


In the following cases, Android will report a ANR error:

– The main thread ("Event processing Thread"/"UI thread") does not respond to input events within 5 seconds

–broadcastreceiver did not complete the return within 10 seconds

Typically, the following practices can cause the ANR

1. Network operation within the main thread

2. Perform some slow disk operations within the main thread (for example, execute SQL queries that are not optimized)

The application should respond in 5 seconds or 10 seconds, otherwise the user will feel "this app is rubbish" "rotten" "Slow" ... Wait a minute

After the high version of the SDK basically have said goodbye in the main thread operation network request, was asked this question I am also quite depressed, really did not encounter, even if the official Google did not restrict, there is a little good programming habits of people will not do so.


The logic should be
1. New Thread for data request
2. After retrieving the data, call the Handler.sendmessage method
3. Updating the UI in the handler handle () method

That's it, or it can be.

Private thread mthread;private Handler mhandler;oncreate:mthread = new Thread (runnable);//Here is a child thread created in the main thread, does not block Uimthread.start ();

Private Runnable Runnable = new Runnable () {void run () {//Do time-consuming data processing//processing complete Mhandler.sendemptymessge (1000);//Here a message informs the UI that it can be updated}};

Mhandler = new Handler () {void Handlemessgae (Message msg) {if (Msg.what = = 1000) {              Update UI} super.handlmessgae (); }};


Android ANR exception and how to fix it

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.