Android code for asynchronous multi-File Download in a single thread

Source: Internet
Author: User
Tags response code

There is now a need to download many files, put in an open port (URL) directory, the files under this directory will change, that is, the file name is not fixed. Now you need to download the files in this directory to the Android device. I found a lot of information and found that I could not list all the files in a URL directory as file names (?). In that case, pack multiple downloaded files into A. ZIP file and put it on the URL. After downloading the file, decompress the file using the code. If there is a file with a Chinese name, it cannot be decompressed normally (this is recorded in another article ). Take another path: the file to be downloaded is associated with all the images in the menu of a ordering system. The file name is the image name of the menu. The menu of the ordering system can be found in the database of the server. In this way, all the menus are traversed. The image names (if any) of each menu and the URL directory are combined into the file download path (the method proposed by the manager) and downloaded through loop traversal.

/*** Download the recipe image, check whether the sdcard is available, set the download update address, and save the location information. */Private void downloadmenuimagecheck () {string status = environment. getexternalstoragestate (); If (! Environment. media_mounted.equals (Status) {toastutils. showfailure (getapplicationcontext (), "sdcard cannot use! "); Return;} requestfileinfo = new requestfileinfo (); requestfileinfo. fileparenturl = "http: // 192.168.1.103: 8181/menupic"; requestfileinfo. saveFilePath = environment. getexternalstoragedirectory (). getabsolutepath () + "/waitab/menupic"; showditil (dialogutil. dialog_downlaod_image_progress); New downlaodupdatetask(cmd.exe cute (requestfileinfo);}/*** find all dishes data * @ return list <menux> */ Private list <menux> updatemenux () {return MDB. findall ();}/*** find all course data * download course image class * traverse the course data list, based on the image name of each dish, spell out the download path * multi-file loop traversal single-thread download ** @ author modify by ZX **/private class downlaodupdatetask extends asynctask <requestfileinfo progressvalue = "" basiccallresult =" ">{@ override protected basiccallresult doinbackground (requestfileinfo... params) {log. D (TAG, "Start doinbackground! "); Final requestfileinfo Req = Params [0]; progressvalue = new progressvalue (0, getstring (R. string. msg_fetching_menu); publishprogress (progressvalue); List <menux> menuxs; menuxs = updatemenux (); If (menuxs = NULL) {dismissditil (dialogutil. dialog_downlaod_image_progress); return New basiccallresult ("can not get menu data! ", False);} // create the directory file basepath = new file (req. SaveFilePath) based on the file path; If (! Basepath. exists () basepath. mkdirs (); int needdownloadimagecount = 0; // record the number of images to be downloaded int finishdownloadimagecount = 0; // record the number of images downloaded long starttime; long endtime; int length = 0; double totallength = 0; int COUNT = 0; Class imageinfo {Public String imagename; Public String imagemenutypegroupx; Public httpurlconnection conn ;} list <imageinfo> imageinfos = new arraylist <imageinfo> (); // retrieve the total number of image files to be downloaded by traversing the menu. The total size and information of the image files that can be connected. For (menux: menuxs) {try {string imagename = menux. getpicname (); // The image name if (stringutils. isnotempty (imagename) {needdownloadimagecount + = 1; Url url = new URL (req. fileparenturl + file. separator + java.net. urlencoder. encode (imagename, "UTF-8"); // If the Dish name is Chinese, in order to solve the garbled problem, change the encoding method httpurlconnection conn = (httpurlconnection) URL. openconnection (); // throws ioexception log. I (tag, "Response code:" + Conn. getresponsecode (); If (httpurlconnection. http_ OK = Conn. getresponsecode () {Length + = Conn. getcontentlength (); string imagemenutypegroupx = menux. getmenutype () + menux. getgroupx (); // course type: imageinfo = new imageinfo (); imageinfo. imagename = imagename; imageinfo. imagemenutypegroupx = imagemenutypegroupx; imageinfo. conn = conn; imageinfos. add (imageinfo) ;}} cat CH (ioexception e) {e. printstacktrace () ;}} if (imageinfos. Size () = 0) {return New basiccallresult ("no image need download! ", False);} totallength = stringutils. bytes2m (length); progressvalue = new progressvalue (0, getstring (R. string. msg_start_download_menuimage); publishprogress (progressvalue); starttime = system. currenttimemillis (); // traverses the connected image information to download for (imageinfo: imageinfos) {try {/* string imagename = menux. getpicname (); // The image name if (stringutils. isnotempty (imagename) {string imagemenutypegroupx = Menux. getmenutype () + menux. getgroupx (); // menu category URL url = new URL (req. fileparenturl + file. separator + java.net. urlencoder. encode (imagename, "UTF-8"); // If the Dish name is Chinese, in order to solve the garbled problem, change the encoding method httpurlconnection conn = (httpurlconnection) URL. openconnection (); // throws ioexception log. I (TAG, "response code:" + Conn. getresponsecode (); If (httpurlconnection. http_ OK = Conn. getresponsecode () {*/string imageme Nutypegroupx = imageinfo. imagemenutypegroupx; string imagename = imageinfo. imagename; inputstream is = imageinfo. conn. getinputstream ();/** you can use either of the following methods to open is. Use the preceding method to test whether it is connected. If it is connected, download and process it again. * inputstream is = Conn. geturl (). openstream (); inputstream is = URL. openstream (); * // create the file path of the next level directory based on the course category; If (stringutils. isnotempty (imagemenutypegroupx) {Path = new file (req. saveFilePath + file. separator + Imagemenutypegroupx); If (! Path. exists () path. mkdir ();} else {Path = new file (req. saveFilePath);} file imagefile = new file (path, imagename); fileoutputstream Fos = new fileoutputstream (imagefile); // progressvalue = new progressvalue (0, "downloading :"); byte buffer [] = new byte [1024]; log. D (TAG, "preper buffer! "); Finishdownloadimagecount + = 1; do {int numread = is. read (buffer); If (numread <= 0) {// publish end break;} count + = numread; FOS. write (buffer, 0, numread); log. D (TAG, "Start FOS. write! "); Endtime = system. currenttimemillis (); double currentlength = stringutils. bytes2m (count); double kbpersecond = count * 1f/(endtime-starttime); // the instant download speed is accurate to milliseconds, and the unit of time is too large, if endtime-starttime is set to 0, the value of // kbpersecond is infinitely large, and the average download speed is calculated. Full expression should be // (count/1000f)/(endtime-starttime)/1000f), // B/MS = kb/s (B = byte) double downloadtotaltime = (endtime-starttime)/1000f; progressvalue. message = string. format ("% d/% d \ t %. 2f M/%. 2f m \ t %. 2fkb/s \ t %. 1f s ", finishdownloadimagecount, needdownloadimagecount, currentlength, totallength, kbpersecond, downloadtotaltime); progressvalue. progress = (INT) (float) count)/length) * Dialogutil. long_progress_max); publishprogress (progressvalue);} while (true); FOS. flush (); FOS. close (); is. close (); //} catch (malformedurlexception e) {e. printstacktrace (); return New basiccallresult ("wrong URL! ", False);} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace (); return New basiccallresult ("error:" + E. getlocalizedmessage (), false) ;}} basiccallresult callresult = new basiccallresult ("Download finish! ", True); callresult. data = needdownloadimagecount + ""; // convert string callresult to int. data2 = string. valueof (finishdownloadimagecount); Return callresult;} @ override protected void onpostexecute (basiccallresult result) {If (result. OK) {log. D (TAG, "Download menu image success! "); Mprogressdialog. setmessage (getstring (R. String. msg_download_image_success); // toastutils. showsuccess (getapplicationcontext ()," Congratulation! Download success! "); If (integer. parseint (result. data)> integer. parseint (result. data2) {toastutils. showlong (getapplicationcontext (), "needdownload:" + result. data + "" + "finishdownload:" + result. data2 + "" + "You shocould put all menu images to server") ;}} else {log. D (TAG, "Download menu image failed! "); Toastutils. showfailure (getapplicationcontext (), "5" + result. message);} disettings. putboolean (getapplicationcontext (), disetask. key_download_menu_image, false); dismissditil (dialogutil. dialog_downlaod_image_progress);} @ override protected void onprogressupdate (progressvalue... values) {log. D (TAG, values [0]. tostring (); mprogressdialog. setprogress (Values [0]. progress); mprogressdialog. setmessage (Values [0]. message) ;}}</imageinfo> </menux> </requestfileinfo> </menux>
Related Article

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.