What's the optimal way to handle a HttpClient on Android?
I can find loads of tutorials that show how should a HttpClient constructed and used in a simple case. But I fail to find any decent documentation for more complex cases.
In my app, I have a bunch of Activities, and each has to be able to communicate with a remote WebServ开发者_运维技巧ice with POST messages using HTTPS. I also have to log in to this service, so I need to manage the login cookie.
Currently, I construct a separate HttpClient for every single Activity in .onStart(), and releasing it in .onStop(). I have a work-queue that contains the objects describing the details of a task that has to communicate with the remote service. I execute these tasks using a single worker AsyncTask. This solution seems to work, but I'm just not sure that it's the most optimal one.
I've thought about 2 other architectures:
- Creating a background Service that handles the HttpClient. This way I might be able to use the same instance thru multiple Activities, and I guess this'd be better. But I'm not sure when to stop this Service and release the HttpClient.
- Create a HttpClient only when needed. So for example when the user clicks a button that initiates a remote call, then I construct the client, set up the cookies and the POST message, execute it, and when it's done I immediately release it. I think this approach is quite bad because of the overhead involved in creating such a client (especially if I use HTTPS).
So anybody that has more insight about the workings of HttpClient and how it should be treated in Android, could you please comment on these approches / share some useful tips?
Thanks
solution 1 is good. You can stop your service once your queue is empty. It combines with your solution 2 in that that the service is started only when needed. When your user clicks a button, you start your service, and for instance you bind to it and give it your request.
Asynctask. Search on Google a method called GrabURl.
精彩评论