title: Android Worker thread freezes Main thread
body: <p>I am working on an app that implements a custom ListView that contains images. I was able to get the listview to download and cache the images, but I would like to move the downloading onto a separate thread. To do so, I created a <em>CachedLogoDownloader</em> class who's goal is to asynchronously download the images and save them in memory to be accessed later by the custom Adapter class. </p>
  
  <p>The problem is that the thread holds up the entire UI. Even when the code in the run() was just a "thread.sleep()" the UI stopped whenever the request for a logo image occurred. Similarly, placing an infinite loop in the run() caused the program to hang indefinitely.</p>
  
  <pre><code>class CachedLogoDownloader{
  
  private HashMap&lt;String, Bitmap&gt; cache = new HashMap&lt;String, Bitmap&gt;();
  Context context;
  ArrayList&lt;String&gt; FIDs;
  Thread runner;
  
  public CachedLogoDownloader(Context inContext){
      this.context = inContext;
  
      //list of company logos (by FID) to be downloaded
      FIDs = new ArrayList&lt;String&gt;();
  
      //asynchronous downloader thread (single thread for lower-end devices. Shouldn't be much slower to get the images, though)
      runner = new Thread(new Runnable() {
          public void run() {
              for(String FID:FIDs){
                  Log.d(Cloud.DEBUG_TAG, "Icon Runnable for: " + FID);
                  Bitmap tempImage = Cloud.lookupIcon(context, FID);
                  cache.put(FID, tempImage);
                  FIDs.remove(FID);                           
              }
  
          }
      });
  }
  
  public Bitmap getLogo(Company aCompany){
  
      String currentFID = aCompany.getFID();
  
      //if the image has already been cached, return the cached image
      if(cache.containsKey(currentFID))
      {
          return cache.get(currentFID);
      }
      else
      {
          //add the logo to the list of logos to be downloaded                
          FIDs.add(currentFID);
  
          //if the downloader thread completed (or hasn't started yet) make it download stuff.
          if(!runner.isAlive()){
              runner.setPriority(Thread.MIN_PRIORITY);
              runner.run();
          }
  
          //return null for now (until next time, whent the image will be in the cache!.)
          return null;
      }
  
  
  
  }
  </code></pre>
  
  <p>}</p>