Package a tool class, take pictures batch Download

Source: Internet
Author: User

In the project, ask to download 30 images at a time. Start using the Google Bitmap fun provided in the imagefetcher to download, but found an egg ache incomparable phenomenon, the picture is always inexplicably few.

Exclude the image address has invalid link, suspect that the number of concurrent download threads too many, after the thread pool is full, use the discard policy to discard the previous download thread.

Ask for yourself, write one yourself.

The thread pool is used here to support concurrent downloads. The thread pool can be chosen by itself, using any of the newsinglethreadexecutor,newfixedthreadpool,newcachedthreadpool. When used, the listener is implemented by itself, and when the number of listening downloads is the same as the number of URL collections, the Listener's onsuccess () method is recalled.

The source code is as follows, hope everybody correct

import java.io.bufferedinputstream;import java.io.bufferedoutputstream;import java.io.file; Import java.io.fileoutputstream;import java.io.ioexception;import java.io.inputstream;import  java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL; import java.net.urlencoder;import java.util.list;import java.util.concurrent.executorservice; Import java.util.concurrent.executors;import java.util.concurrent.rejectedexecutionexception;import  android.util.Log;/** *  Batch image Download class   download class without interaction with the interface  * *  @Description:  * *   @author- liubing *  @create- 2013-5 -6 *  @modify  by: *  @modify- time */public class downloadservice {     private  static String TAG =  "Downloadservice"  ;     public  static final int io_buffer_size = 8 * 1024;     private static  final string cache_filename_prefix =  "Cache_";     private  Static executorservice single_task_executor = null;     private  static ExecutorService LIMITED_TASK_EXECUTOR = null;      private static final executorservice full_task_executor = null;      private static final ExecutorService DEFAULT_TASK_EXECUTOR ;      private static object lock = new object ();      static {           //  single_task_executor =  (Executorservice)             // executors.newsInglethreadexecutor ();            limited_task_executor  =  (Executorservice)  Executors                    . newfixedthreadpool (1);            // FULL_TASK_EXECUTOR =  (Executorservice)             // executors.newcachedthreadpool ();            default_task_executor = limited_task_executor  ;     };     //  Download Status monitoring, providing callbacks       DownloadStateListener listener;     //  Download Catalog       private String downloadPath;     //  Download Link Collection       private list<string> listurl;     //  Number of downloads      private  int size = 0;     //  Download Complete Callback interface       public interface downloadstatelistener {            public void onfinish ();            public void onfailed ();      }     public  downloadservice (string downloadpath, list<string> listurl,               downloadstatelistener listener)  {            this.downloadPath = downloadPath;            this.listURL = listURL;            this.listener = listener;     }      /**      *  does not provide settings       */      public void setdefaultexecutor ()  {     }      /**      *  Start Download        */     public void startdownload ()  {            //  first detects if path exists            file downloaddirectory = new file (downloadpath );            if  (!downloaddirectory.exists ())  {               downloaddirectory.mkdirs ();           }           for  (final String  url : listurl)  {                //capture thread pool denied execution exception                 try {                     //  threads into the thread pool                      default_task_executor.execute (new  Runnable ()  {                           @Override                            public void run ()  {                              downloadbitmap (URL);                          }                    });               }  catch  (rejectedexecutionexception e)  {                    e.printstacktrace ();                    log. e (TAG,   "Thread pool rejected error");                     listener.onfailed ();               } catch  (exception e)  {                    e.printstacktrace ();                      Listener.onfailed ();               }           }     }      /**      *  Download Images       *       *  @param  urlString      *  @return       */     private file downloadbitmap ( string urlstring)  {          String fileName = urlString;            //  How to name images             final file cachefile = new file (CreateFilePath (new  file (                     downloadpath),  filename);           HttpURLConnection urlConnection = null;           BufferedOutputStream out = null;            try {                final url url = new url (urlstring);               urlconnection =  (HttpURLConnection)  url.openconnection ();                final inputstream in =  new bufferedinputstream (                         urlconnection.getinputstream (),  io_buffer_size);               out =  new bufferedoutputstream (New fileoutputstream (cachefile),                           io_buffer_size);                int b;                while  ((b = iN.read ())  != -1)  {                    out.write (b);               }                //  one per download, count the numbers                statdownloadnum ();                return cachefile;          } catch   (final ioexception e)  {                //  A download failure indicates that the bulk download did not succeed                log. e (tag,  "download "  + urlString +  "  Error ");               listener.onfailed ();           } finally {                if  (urlconnection != null)  {                     Urlconnection.disconnect ();               }               if  (out  != null )  {                     try {                         out.close ();                    } catch  (final IOException  e)  {                         log. e (tag,  "Error in downloadBitmap  -  " + e);                    }               }          }            return null ;     }      /**      * Creates a constant cache file  path given a target cache directory and an       * image key.      *      *  @param  cacheDir       *  @param  key      *  @return        */     public static string createfilepath ( File cachedir, string key)  {            try {               //  Use URLEncoder to ensure we have a valid filename, a  tad hacky               //  but it will do for                // this example               &Nbsp;return cachedir.getabsolutepath ()  + File.separator + CACHE_FILENAME_PREFIX                          + urlencoder.encode (Key.replace ("*",  ""),  "UTF-8"  );           } catch  (final  Unsupportedencodingexception e)  {               log. e (tag,  "createfilepath - "  + e);           }           return  null ;     }     /**       *  Statistics Download Number       */     private void  statdownloadnum ()  {           synchronized  (lock )  {                size++;                if  (Size == listurl .size ())  {                     log. d (tag,  "download finished total "  + size);                     //  Release Resources                      default_task_executor.shutdownnow ();                     //  if the number of successful downloads matches the number of  url in the list, the download is successful     &nbsP;               listener.onfinish ( ); //  download successful callback               }           }     }}

New downloadservice (  "/mnt/sdcard/test",  listurl, new downloadstatelistener ()  {                                @Override                 public void onfinish ()  {                      //image download Successful, implement your code                                    }                               @Override            &Nbsp;    public void onfailed ()  {                     //image download Successful, implement your code                                    }           }). Startdownload ();


Package a tool class, take pictures batch Download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.