0

I need to download a number of bitmaps from server into android. I want to use an AsyncTask executed using .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR). But my executor is getting overwhelmed. So I figure, if I put a delay, that should help. So my question: how do I put a delay on an executor? I am thinking of using handler.postDelay but that only accepts runnables. Is there a way to get it to work with an executor?

A good solution might be to run 20 calls at a time and then wait 100 milliseconds to run the next 20. Does anyone know a way to do that on android?

@pete

I am using one thread per call. I wasn't sure if multiple calls in one thread would cause a problem.

@Override
protected Bitmap doInBackground(Void... params) {
   try {

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDoInput(true);
      conn.connect();
      InputStream is = conn.getInputStream();
      return BitmapFactory.decodeStream(is);
   } catch (IOException e) {
      e.printStackTrace();
      return null;
   }
}
Cote Mounyo
  • 13,817
  • 23
  • 66
  • 87
  • What are you doing with the Bitmaps you create from the images you retrieve? You will likely run out of memory if you aren't writing them to file and then calling Bitmap.recycle(). – Rick Falck Oct 23 '13 at 20:01
  • 1
    Have you considered using an IntentService for each image? If not see my answer to: http://stackoverflow.com/questions/19291462/android-download-multiple-files-one-after-another-and-show-progress-in-listview/19292348#19292348 – cYrixmorten Oct 23 '13 at 20:06

2 Answers2

0

If you just want to add a pause, use the following in doInBackground:

count = 1;
// use your loop of choice
for(int i = 0; i < n; i++) {
            // Do your stuff here...
    if(count % 20) { // Sleep every 20 iterations
        Thread.sleep(100);
    }
    count++;
}

However, as @petey stated, code would be a better help. Depending on what you're doing there might be a better alternative than using an AsyncTask (maybe an IntentService).

Jason
  • 1,238
  • 1
  • 15
  • 18
  • Like Rick asked, what are you doing with the Bitmaps? If they are going into some kind of ListView/GridView, then [Universal Image Loader](https://github.com/nostra13/Android-Universal-Image-Loader) might be a better solution. Like @physphil, I've used it and it works great. – Jason Oct 23 '13 at 22:23
0

+1 to cYrixmorten's idea of using an IntentService. In my experience it's much more reliable than using an AsyncTask, especially when downloading a large amount of information.

If you're specifically dealing with downloading images, have you looked at Universal Image Loader? It's an open source library designed for that specific purpose. I've used it in a couple of my projects and I find it very easy to implement, and it handles image downloading, threading and caching for you.

Hope this helps!

physphil
  • 233
  • 2
  • 9