Avoid ANR in Android Development

Source: Internet
Author: User

ANRs ("Application Not Responding"), which means "Application has no response".

Android reports an ANR error in the following cases:

-The main thread ("event processing thread"/"UI thread") does not respond to the input event within 5 seconds.

-BroadcastReceiver does not return results within 10 seconds.

Normally, the following operations will cause ANR

1. Perform network operations in the main thread

2. Perform some slow disk operations in the main thread (for example, executing SQL queries that have not been optimized)

The application should respond within 5 or 10 seconds. Otherwise, the user will feel "this application is very spam", "rotten", and "slow "... And so on.

Some data (for example, Nexus One)

•~ 0.04 MS-write A byte from A-> B through the pipeline process from B-> A; or (from dalvik) read A simple/proc file

•~ 0.12 MS-one RPC call of the Binder again by A-> B by B->

•~ 5-25 MS-never buffered flash
•~ 5-200 + (!) MS-write something to the buffer flash (below is the specific data)

• 16 MS-one frame in a 60fps video

• 41 MS-one frame in a 24 FPS video

• 100-200 MS-human perception of slow action

• 108/350/500/800 MS-3G network ping (variable)

•~ 1-6 + seconds-get 6 k Data on 3G network through HTTP

Android. OS. AsyncTask

AsyncTask can be easily used with the UI thread. This class can execute some operations in the background and publish the results to the UI thread at the end of the execution, it does not need to be controlled by threads or handler.

Example:

private class DownloadFilesTask extends AsyncTask {protected Long doInBackground(URL... urls) {  // on some background threadint count = urls.length;long totalSize = 0;for (int i = 0; i < count; i++) {totalSize += Downloader.downloadFile(urls[i]);publishProgress((int) ((i / (float) count) * 100));}return totalSize;     } protected void onProgressUpdate(Integer... progress) {  // on UI thread!setProgressPercent(progress[0]);} protected void onPostExecute(Long result) {  // on UI thread!showDialog("Downloaded " + result + " bytes");}} new DownloadFilesTask().execute(url1, url2, url3);  // call from UI thread!private boolean handleWebSearchRequest(final ContentResolver cr) {            ...new AsyncTask() {    protected Void doInBackground(Void... unused) {    Browser.updateVisitedHistory(cr, newUrl, false);    Browser.addSearchUrl(cr, newUrl);    return null;    } }.execute()            ...    return true; }
Key Points of AsyncTask

1. It must be called from the main thread, or the thread contains Handler or logoff.

2. Do not use AsyncTask in a library that may be called by another AsyncTask (AsyncTask cannot be reentrant)

3. If you call an activity, the activity process may exit before the end of AsyncTask. For example:

  • The user exits the activity.
  • Insufficient system memory
  • The system temporarily saves the activity status for future use
  • The system has killed your thread.

If the work in AsyncTask is very important, use ......

Android. app. IntentService

The Eclair (2.0, 2.1) Documentation says:

"An abstract Service that serializes the handling of the Intents passed upon service start and handles them on a handler thread. to use this class extend it and implement onHandleIntent (Intent ). the Service will automatically be stopped when the last enqueued Intent is handled."
A little confusing, so... Almost no one uses it

Froyo (2.2) documentation, clarified ....

Android. app. IntentService

"IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. clients send requests through startService (Intent) CALS; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This 'work queue processor 'pattern is commonly used to offload tasks from an application's main thread. the IntentService class exists to simplify this pattern and take care of the mechanic. to use it, extend IntentService and implement onHandleIntent (Intent ). intentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread-they may take as long as necessary (and will not block the application's main loop ), but only one request will be processed at a time."

Benefits of IntentService
  • When processing Intent, a corresponding Service is generated.
  • The Android process processor will try not to kill you
  • Very easy to use

IntentService application in calendar

public class DismissAllAlarmsService extends IntentService {@Override public void onHandleIntent(Intent unusedIntent) {ContentResolver resolver = getContentResolver();...resolver.update(uri, values, selection, null);}}in AlertReceiver extends BroadcastReceiver, onReceive():  (main thread)    Intent intent = new Intent(context, DismissAllAlarmsService.class);    context.startService(intent);
Other skills

1. When you start AsyncTask, Immediately disable the UI elements (buttons and so on ).

2. Some animations are displayed, indicating that they are being processed.

3. Use the progress bar dialog box

4. Use a timer as the time-consuming warning. Start the timer at the beginning of AsyncTask and cancel the timer in the onPostExecute method of AsyncTask.

5. Use all the above methods in combination when you are not sure how long it will take

Summary
  • Leave the main thread!
  • Disk and network operations cannot be completed immediately
  • Understand what sqlite is doing
  • Great progress

PS. In the video lecture, the author also mentioned that almost all functions and tasks of the Chrome team will be done in the Child thread in order to avoid the death of Jank (Response timeout. This is also worth learning from in Android.

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.