What is an ANR?
When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI Thread, perform long operation such as network access or database queries will block the whole UI.
When the thread is blocked, no event can be dispatched, including drawing events. From the user’s perspective, the application appears to hang. Even worse, if The UI thread is blocked for more than a few seconds (5 sec) the user OS presented with the infamous “Application not responding” (ANR) dialog.
How to Prevent ANR?
The Android UI toolkit is not thread safe. So you must not manipulate your UI from a worker thread – you must do all manipulation to your user interface from the UI thread,
Thus, there are simply two rule to Android single thread model.
1. Do not block the UI Thread
2. Do not access the Android UI toolkit from outside the UI thread?
If you have operation perform that are not instantaneous, you should make sure to do them in separate thread (“Background” or “Worker” threads).
However, note that you cannot update the UI from any thread other than the UI Thread or the “main” thread.
To fix problem, Android offers several ways to access the UI thread from other thread.
1. Activity. runOnUiThread(Runnable)
AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in worker tread and publish the result on the UI Thread, without requiring you to handle thread and /or handlers yourself.
To use it, you must subclass AsyncTask and Implement callback methods
a. doInBackground() :- Which runs in pool of background thread.
b. onPostExecute() :- Which delivers the result from doInBackground() and run in the UI thread.
So you can safety update you UI, You can then run the task by calling execute () from the UI thread.
In some situations, the method you implement might be called from more than one thread,
This is primarily true for methods that can be called remotely- such as methods in a bound service.
A bound service is an implementation of the Service class that allows other applications to bind to it and interact with it. To provide bonding for a service, you must implement this OnBind() call-back method. This method return an IBinder object that defines the Programming interface that client can use to interact with the service.