(Android) Threaded httpClient task, without blocking UI?
I've made an application that Fetches a Webpage from the internet, based on user input, wich worked. The fetching goes in different steps: post with String from edittext as parameter, after some parsing this returns an Array of names wich are displayed in an AlertDialog. When the user picks one, it makes another post with that String as parameter.
This works, but now I want to make it Threaded (or similar), so that the UI doesn't get unresponsive. I tried Threads, Runnables and AsyncTask, but I just cannot find out a construction to get the fetching in a single Thread, and also be able to return that array and pick a name, WITHOUT making a new instance of my HttpClient. This would erase Cookies yo开发者_如何学Gou see...I've spent about a whole week to figuring this out, but just don't see it :(
So anyone got an idea? thanks !
For each of your HTTP accesses, you can create a separate AsyncTask subclass, then instantiate each one of them in turn, and execute them. On the web there are many examples on how to use AsyncTask to access HTTP, e.g. here or here (just google for something like this).
The main idea to grasp there, is to do all the network-related operations inside the doInBackground
method body of the AsyncTask.
As Ted Hopp said, you can let the HttpClient instance be a private member of your Activity (or whatever class holds the two AsyncTasks), so that the first AsyncTask will create it, and the second one can just use the same.
You can use two AsyncTask subclasses, one for each request. Give the subclasses access to a variable in your activity class that stores the HttpClient object.
精彩评论