Avoid the use of unresponsive methods in Android development (application not responding, ANR) _android

Source: Internet
Author: User

The worst thing that happens in the app is the pop-up application no response "application not Responding" (ANR) dialog box. This lesson is about how to keep application responses and avoid ANR.

What triggers ANR

Typically, the system displays ANR when the application cannot respond to user input. For example, if an application blocks a (frequently requested network) UI thread on I/O operations, the system cannot handle user input events. Alternatively, in the UI thread, the app spends a lot of time building complex classes, or computing the next action in the game. It is important to ensure that these operations are efficient, but the most efficient code also takes time.

In any case, do not perform time-consuming tasks on the UI thread, instead create a worker thread that operates in this thread. This keeps the UI thread running and prevents the system from ending the application because the code is stuck.
In Android, the Activity Manager and Window Manager System Services monitor the responsiveness of applications. Android will pop up the ANR dialog box when it detects the following scenarios:

1. No response to user input event in 5 seconds
2.BroadcastReceiver not done in 10 seconds

How to avoid ANR

The Android app runs in a single thread, called the UI thread or the main thread. This means that all of your application work is in the UI thread, and if it takes a long time to complete, it triggers ANR because the application cannot manipulate input events or broadcasts at this time.

Therefore, any method that the UI line Chengri should do as much light as possible, especially activity in the lifecycle method, like OnCreate (), Onresume (). Potentially time-consuming operations, such as network, database, or expensive computing (like changing picture size) should be done in a worker thread (or, in the case of a database operation, through an asynchronous request).

The most efficient approach is to create a worker thread using the Asynctask class for time-consuming operations. Inheritance Asynctask implements the Doinbackground () method to perform the work. To send the progress to the user, call Publishprogress (), which triggers the onprogressupdate (), Example:

Copy Code code as follows:

Private class Downloadfilestask extends Asynctask<url, Integer, long> {
Do the long-running work
Protected Long doinbackground (URL ... urls) {
int count = Urls.length;
Long totalsize = 0;
for (int i = 0; i < count; i++) {
TotalSize + + downloader.downloadfile (urls[i]);
Publishprogress ((int) ((I/(float) count) * 100));
Escape early if Cancel () is called
if (iscancelled ()) break;
}
return totalsize;
}

This is called a call publishprogress ()
protected void Onprogressupdate (Integer ... progress) {
Setprogresspercent (Progress[0]);
}

This is called when Doinbackground () is finished
protected void OnPostExecute (Long result) {
Shownotification ("downloaded" + result + "bytes");
}
}

To execute this worker thread, simply create an instance and invoke execute ():

Copy Code code as follows:
New Downloadfilestask (). Execute (URL1, URL2, URL3);

Although more complex than Asynctask, you may still want to create your own thread or Handlerthread class, and if you do, you should call Process.setthreadpriority (Thread_priority_background) Set the thread priority to "background". If not, the thread will still slow down the application because it is the same as the UI thread priority.

If you implement thread or Handlerthread, make sure that the UI thread is not blocked because it waits for the worker thread to finish executing. Do not call thread.wait () or Thread.Sleep (), but provide a handler for the callback after the task has been executed. With this design, the UI thread remains responsive and avoids the ANR dialog box.

Special emphasis on Broadcastreceiver execution time means you want to: Spread your work to a background thread, like saving settings or registering notification. Perform intensive tasks (intensive tasks) and should use Intentservice.

Tip: You can use Strictmode to help you find potentially time-consuming operations on the UI thread

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.