On Tue, Sep 28, 2010 at 4:35 AM, Jose Luis Montes <[email protected]> wrote: > I have an app in which there are several requests to a server in internet > (http), for example to retrieve images in threads outside the main UI > process. > The thing is that I have a Thread that manage the request with a while(!end) > loop and in the end a Thread.sleep(500) that checks if there are new > unhandled requests. As I read here [1] I know that this is not a good > practice. And users have complain about ANR (app not responding) in several > cases.
If you are getting an ANR, then you are not handling your background thread properly. ANRs are triggered by the *main application thread* being blocked. > Knowing that obviously I want to refactor all the way my app manage the > requests and I want to do that the best way. > So, the question is; what is the best approach for doing this? A service? a > broadcast receiver and send intents when I need a request to be handled? Since we have no good way of identifying your criteria for "best", all we can do is give you options. Here are two: An IntentService would be a close analog to what you are doing today, with the side benefit of dumping the sleep() call. The IntentService would do the download, then let the activity know about the downloaded image via a private broadcast, or createPendingResult(), or something. The activity would use startService() to ask the IntentService to do the download. Rather than a single thread, you could use an AsyncTask per download. This allows for some parallelism, since each AsyncTask gets its own thread out of a thread pool. Due to possible activity configuration changes (e.g., orientation), it is probably better to have these tasks coordinated via a regular Service, but you could have an Activity manage its own if you are careful. -- Mark Murphy (a Commons Guy) http://commonsware.com | http://github.com/commonsguy http://commonsware.com/blog | http://twitter.com/commonsguy Android Training in Atlanta: http://bignerdranch.com/classes/android -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en

