I am requesting information from a web service in my android app. The web service returns a list of items, each item having a base64 image and some info
First method: simply access the web service and get the result. This means freeze of UI until data is downloaded. Not a good solution
Second method: put the data download in a thread, and display a progress bar with a message.
private void StartGettingData()
{
viewInfo = new Runnable(){
public void run() {
getData(); //from the web service
}
};
Thread thread = new Thread(null, viewInfo, "MagentoBackground");
thread.start();
progressDialog = ProgressDialog.show(TracksListActivity.this,
"Please wait...", "Retrieving data from WEB...", true);
}
private void getData(){
{
get data from web service into a list and then
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
public void run() {
populate t开发者_如何学Pythonhe listview adapter with info from the web service result list and
progressDialog.dismiss();
generalTrackInfoAdapter.notifyDataSetChanged();
}
};
This shows a nice loading image and the message. The user will have to wait until all the download is complete. I don't know how to cancel the getdata() thread.
Third method: I would like to have something like, the user presses a button to get data, a thread downloads item by item from the web service and immediate shows it in the list. The use can always cancel the request with a button press.
But, how to do this ? Or is there another way ?
You can use AsyncTask for threading, basics: painless threading, example:Multithreading For Performance(image downloader).
Because using the class thread or the interface runnable your code becomes more complicated and more difficult to read. It becomes even worse when you implement complex operations that require frequent UI updates.
The goal of AsyncTask is to take care of thread management for you.
The basic structure is:
public class DownloaderTask extends AsyncTask<String, String, String>{
protected void onPreExecute(){}
protected String doInBackground(String....args){
//do something in background
}
protected void onProgressUpdate(String str){}
protected void onPostExecute(String result){
//..update ui
}
}
...to start your task e.g.:
public void onClick(View v){
new DownloaderTask().execute("param");
}
The method doInBackground() executes automatically on a worker thread
onPreExecute(), onPostExecute() and onProgressUpdate() are all invoked on the UI thread
The value returned by doInBackground() is sent to onPostExecute()
You can call publishProgress() at anytime in doInBackground() to execute onProgressUpdate() on the UI thread
You can cancel the task at any time, from any thread
精彩评论