Jimtronic
Jimtronic

Reputation: 1209

Looking for good example of using get() with an AsyncTask in android

I'm curious about the get(long, java.util.concurrent.TimeUnit) function in AsyncTask, but I'm having a hard time locating an example of it's usage.

get(long, java.util.concurrent.TimeUnit)

Can anyone provide an example of it's use?

Upvotes: 12

Views: 20628

Answers (2)

neteinstein
neteinstein

Reputation: 17613

Another use of AsyncTask is to know when several AsyncTasks have processed:

AsyncTask1 a1 = new AsyncTask();
AsyncTask1 a2 = new AsyncTask();

a1.execute();
a2.execute();

a1.get();
a2.get();

Log.d("Example", "a1 and a2 have both finished, you can now proceed");

Upvotes: 4

citizen conn
citizen conn

Reputation: 15390

It appears as though AsyncTask.get() blocks the caller thread, where AsyncTask.execute() does not.

You might want to use AsyncTask.get() for test cases where you want to test a particular Web Service call, but you do not need it to be asynchronous and you would like to control how long it takes to complete. Or any time you would like to test against your web service in a test suite.

Syntax is the same as execute:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}

new DownloadFilesTask().get(5000, TimeUnit.MILLISECONDS);

Upvotes: 15

Related Questions