开发者

How to properly use AsyncTask

I want to capture a frame buffer from a camera surface preview and send those buffers to another function to be processed / POSTed somewhere on the web.

The Android Dev guide gives this example: http://developer.android.com/reference/android/os/AsyncTask.html

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

Here's how you execute it:

new DownloadFilesTask().execute(url1, url2, url3);

Is this entire operation one big AsyncTask (in other words, is that loop going to sit there and wait for each file to download synchronously) while the entire task works in the background, or is this going to start up multiple threads for each URL that was passed?

Related to my project, would it be reasonable to simply create a brand new AsyncTask every single time I want to capture a frame buffer? Something along the lines of:

//for each frame buffer i want to process:
    new FrameProcessorTask().execute(开发者_开发技巧byte[]);


It will be a single thread, taken from a managed thread pool. The argument ellipsis is simply the input to your doInBackground method. As you can see from the example, no threads are spawned in there. If you want to use one thread per URL, you'll have to create a new AsyncTask for each of them.


It is one thread that is looping over the data.

You can do the latter too.

With the 2nd option, you need to take the heap size into account, as the handset only has a limited amount of memory and many parallel threads, all downloading in big buffers may overrun the available memory.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜