connecting to a webservice from android
I'm writing an android app that will connect to a REST/JSON webservice. Users will be retrieving information, uploading comments, downloading and uploading images etc.
I know that I shouldn't keep all this network communication in the Activity/UI thread, as it will cause ANRs. What I'm confused about is whether I should use an AsyncTask or a Service with "manual" threading to accomplish this;
With a Service, I'd simply have a public method for each method in the webservice's API. I'd then implement threading within each of these methods.
If I used an AsyncTask, I would create a helper class that defined AsyncTasks for each method in the webservice's API.
Which method is preferred? Interaction with the webservice will only happen while the user is in the Activity. Once they switch to another application, or exit the program, there is no need for communication with the webservice.
I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks of the UI-thread.
It's also easy to implement eg onProgressUpdate if you need to show a progress bar of some sort while running your requests.
我推荐IntentService
,它的实现并不复杂得多,而且肯定更强大,因为它并不与ActivityLifecycle紧密结合(特别是onConfigurationChange()
)
This library provides an async wrapper to Apache httpclient available in Android.
http://loopj.com/android-async-http/
链接地址: http://www.djcxy.com/p/74520.html上一篇: 无法在Android上使用Web服务
下一篇: 连接到android的web服务