Chat app vs REST app - use a thread in an Activity or a thread in a Service?
In Virgil Dobjanschi's talk, "Developing Android REST client applications" (link here), he said a few things that took me by surprise. Including:
Don't run http queries in threads spawned by your activities. Instead, communicate with a service to do them, and store the information in a ContentProvider. Use a ContentObserver to be notified of changes.
Always perform long running tasks in a Service, never in your Activity.
Stop your Service when you're done with it.
I understand that he was talking about a REST API, but I'm trying to make it fit with some other ideas I've had for apps. One of APIs I've been using uses long-polling for their chat interface. There is a loop http queries, most of which will time out.
This means that, as long as the app hasn't been killed by the OS, or the user hasn't specifically turned off the chat feature, I'll never be done with the Service, and it wil开发者_运维问答l stay open forever. This seems less than optimal.
Long question short:
For a chat application that uses long polling to simulate push and immediate response, is it still best practice to use a Service to perform the HTTP queries, and store the information in a ContentProvider?
Don't run http queries in threads spawned by your activities. Instead, communicate with a service to do them, and store the information in a ContentProvider. Use a ContentObserver to be notified of changes.
I have yet to view the presentation, though I have reviewed the slides. I have serious reservations about the ContentProvider
portion of the proposed architecture.
Always perform long running tasks in a Service, never in your Activity.
Everybody has their pet "always" and "never" statements, myself included. I would hesitate to put this in the "always" category. Using a Service
as a home base of long-running tasks is a fine strategy, but it too has its issues (e.g., in a screen rotation, unbindService()
will destroy the Service
before the next bindService()
kicks in, if there are no other bound connections, leaving you with gobs and gobs of connection bookkeeping if you have a complex app).
For a chat application that uses long polling to simulate push and immediate response, is it still best practice to use a Service to perform the HTTP queries, and store the information in a ContentProvider?
It is a practice. IMHO, the jury is still very much out as to whether it is a best practice.
精彩评论