I have an android app in which there are many scenarios where request and response happens to-from server. For example:login i.e. authentication. When user enters username and password, then the credentials are verified against the one responded by Server.
But sometimes what happens is that due to slow network the response comes late and android pop-up a force close dialog box, which is highly embarrassing.
I was thinking that is there a way to segregate the code which hits the server in some separate thread and till it gets me a response. I may show a progress bar instead of force close. Is it a good solution?
Example code:
//this code will be called when user presses Login button on UI
public void authenticate(View view) {
//the logic for authentication
if(authentication==true){
//go to home page
}
}
In the above code how can I separate the logic for authentication so that force close does not occur when response is late as expected.
I would also appreciate any other better approach to tackle such scenarios of force close.
Do not include any task which takes time to execute in your main thread. You should do httpCommunication in different thread. and it will avoid this ANR.
What docs says >>
In Android, application responsiveness is monitored by the Activity Manager and Window Manager system services. Android will display the ANR dialog for a particular application when it detects one of the following conditions:
No response to an input event (e.g. key press, screen touch) within 5 seconds
A BroadcastReceiver hasn’t finished executing within 10 seconds
Read this document specially created for Designing for responsiveness and to avoid ANR
You can use AsyncTask as well.