Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 559
Jimtronic Avatar asked Aug 15 '11 20:08

Jimtronic


People also ask

What is AsyncTask in android with example?

Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.

What is the use of AsyncTask?

This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field. onPostExecute(Result) , invoked on the UI thread after the background computation finishes.

How can I use AsyncTask in different activities in android?

AsyncTask class is firstly executed using execute() method. In the first step AsyncTask is called onPreExecute() then onPreExecute() calls doInBackground() for background processes and then doInBackground() calls onPostExecute() method to update the UI.

Why did AsyncTask get deprecated?

Why Android AsyncTask is Deprecated? Here is the official reason it is deprecated. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.


1 Answers

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);
like image 175
citizen conn Avatar answered Sep 22 '22 14:09

citizen conn