开发者

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?


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);


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜