"Android-011" "multi-threaded download"

Source: Internet
Author: User
<span id="Label3"></p><strong><strong>Android Learning Directory</strong></strong><strong><strong>Project Source Download</strong></strong><strong><strong>multi-threaded Download</strong></strong> <blockquote> <blockquote> <p>Principle: the server CPU is allocated the same time slice for each thread, the server bandwidth is allocated evenly to each thread, so the more threads the client opens, the more server resources can be preempted.</p> </blockquote> </blockquote><strong><strong>determine how much data each thread downloads</strong></strong> <ul> <ul> <li>Send HTTP request to</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs avrasm"> <span class="hljs-string">"http://192.168.1.102:8080/editplus.exe"</span><span class="hljs-comment">; </span> URL url = new URL(path)<span class="hljs-comment">;</span> HttpURLConnection conn = (HttpURLConnection) url<span class="hljs-preprocessor">.openConnection</span>()<span class="hljs-comment">;</span> conn<span class="hljs-preprocessor">.setReadTimeout</span>(<span class="hljs-number">5000</span>)<span class="hljs-comment">;</span> conn<span class="hljs-preprocessor">.setConnectTimeout</span>(<span class="hljs-number">5000</span>)<span class="hljs-comment">;</span> conn<span class="hljs-preprocessor">.setRequestMethod</span>(<span class="hljs-string">"GET"</span>)<span class="hljs-comment">; </span></code></pre></pre> <ul> <ul> <li>Get the total length of the file, and then create a temporary file of the same length</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs go"> <span class="hljs-keyword">if</span>(conn.getResponseCode() ==<span class="hljs-number"> 200</span>){ <span class="hljs-comment">//获得服务器流中数据的长度</span> <span class="hljs-typename">int</span> length = conn.getContentLength(); <span class="hljs-comment">//创建一个临时文件存储下载的数据</span> <span class="hljs-built_in">new</span><span class="hljs-string">"rwd"</span>); <span class="hljs-comment">//设置临时文件的大小</span> raf.setLength(length); raf.<span class="hljs-built_in">close</span>();</code></pre></pre> <ul> <ul> <li>Determine how much data the thread downloads</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs glsl"> <span class="hljs-comment">//计算每个线程下载多少数据</span> <span class="hljs-keyword">int</span><span class="hljs-built_in">length</span> / THREAD_COUNT;</code></pre></pre><strong><strong>calculate the start and end locations of each Thread's download data</strong></strong><pre class="prettyprint"><code class=" hljs objectivec"> <span class="hljs-keyword"><span class="hljs-keyword"></span> for</span>(<span class="hljs-keyword"><span class="hljs-keyword">int</span></span> <span class="hljs-keyword"><span class="hljs-keyword">ID</span></span>=<span class="hljs-number"><span class="hljs-number">1</span></span>;<span class="hljs-keyword"><span class="hljs-keyword">ID</span></span><=<span class="hljs-number"><span class="hljs-number">3</span></span>;<span class="hljs-keyword"><span class="hljs-keyword">ID</span></span>++){<span class="hljs-comment"><span class="hljs-comment">//calculate the starting and ending positions of each Thread's download data</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>StartIndex = (<span class="hljs-keyword"><span class="hljs-keyword">ID</span></span>-<span class="hljs-number"><span class="hljs-number">1</span></span>) * blockSize;<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>EndIndex =<span class="hljs-keyword"><span class="hljs-keyword">ID</span></span>* blockSize-<span class="hljs-number"><span class="hljs-number">1</span></span>;<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">ID</span></span>= = Thread_count) {endIndex = length; }<span class="hljs-comment"><span class="hljs-comment">//open thread, Start downloading data as calculated start end</span></span>New Downloadthread (startIndex, endIndex,<span class="hljs-keyword"><span class="hljs-keyword">ID</span></span>)<span class="hljs-variable"><span class="hljs-variable">. Start</span></span>(); }</code></pre><strong><strong>Send request to, request data from start to end position</strong></strong><pre class="prettyprint"><code class=" hljs go">String Path =<span class="hljs-string"><span class="hljs-string">"http://192.168.1.102:8080/editplus.exe"</span></span>; URL url =<span class="hljs-built_in"><span class="hljs-built_in">New</span></span>URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout<span class="hljs-number"><span class="hljs-number">(</span> the</span>); Conn.setconnecttimeout<span class="hljs-number"><span class="hljs-number">(</span> the</span>); Conn.setrequestmethod (<span class="hljs-string"><span class="hljs-string">"GET"</span></span>);<span class="hljs-comment"><span class="hljs-comment">//request Partial data to the server</span></span>Conn.setrequestproperty (<span class="hljs-string"><span class="hljs-string">"Range"</span></span>,<span class="hljs-string"><span class="hljs-string">"bytes="</span></span>+ StartIndex +<span class="hljs-string"><span class="hljs-string">"-"</span></span>+ endIndex); Conn.connect (); * Download the requested data and store it in a temporary file<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(conn.getresponsecode () = =<span class="hljs-number"><span class="hljs-number">206</span></span>) {inputstream is = Conn.getinputstream (); Randomaccessfile RAF =<span class="hljs-built_in"><span class="hljs-built_in">New</span></span>Randomaccessfile (getfilename (path),<span class="hljs-string"><span class="hljs-string">"rwd"</span></span>);<span class="hljs-comment"><span class="hljs-comment">//specify from which location to start storing data</span></span>Raf.seek (startIndex);<span class="hljs-typename"><span class="hljs-typename">byte</span></span>[] B =<span class="hljs-built_in"><span class="hljs-built_in">New</span></span> <span class="hljs-typename"><span class="hljs-typename">byte</span></span><span class="hljs-number"><span class="hljs-number">[1024x768</span></span>];<span class="hljs-typename"><span class="hljs-typename">int</span></span> <span class="hljs-built_in"><span class="hljs-built_in">Len</span></span>; While ((<span class="hljs-built_in"><span class="hljs-built_in">Len</span></span>= Is.read (b))! =<span class="hljs-number"><span class="hljs-number">-1</span></span>) {raf.write (b,<span class="hljs-number"><span class="hljs-number">0</span></span>,<span class="hljs-built_in"><span class="hljs-built_in">Len</span></span>); } raf.<span class="hljs-built_in"><span class="hljs-built_in">Close</span></span>(); }</code></pre><strong><strong>multi-threaded download with breakpoint continuation</strong></strong> <ul> <ul> <li> defines an int variable that records the total length of data downloaded by each thread, and then adds the download start location for that thread, resulting in the next download, where the thread starts, and the resulting result is cached in the cache file </li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs go"> <span class="hljs-comment">//用来记录当前线程总的下载长度</span> <span class="hljs-typename">int</span> total =<span class="hljs-number"> 0</span>; while((<span class="hljs-built_in">len</span> = is.read(b)) !=<span class="hljs-number"> -1</span>){ raf.write(b,<span class="hljs-number"> 0</span><span class="hljs-built_in">len</span>); <span class="hljs-built_in">len</span>; <span class="hljs-comment">//每次下载都把新的下载位置写入缓存文本文件</span> <span class="hljs-built_in">new</span><span class="hljs-string">".txt"</span><span class="hljs-string">"rwd"</span>); <span class="hljs-string">""</span>).getBytes()); raf2.<span class="hljs-built_in">close</span>(); }</code></pre></pre> <ul> <ul> <li>The next time the download begins, the value in the cache file is read first, and the resulting value is the beginning of the line assigns</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs vhdl"> <span class="hljs-keyword">new</span> FileInputStream(<span class="hljs-keyword">file</span>); <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> InputStreamReader(fis)); <span class="hljs-typename">String</span> text = br.readLine(); <span class="hljs-typename">Integer</span>.parseInt(text); //把读到的值作为新的开始位置 startIndex = newStartIndex; fis.close();</code></pre></pre> <ul> <ul> <li>After all three threads have been downloaded, delete the cache file</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs d"> RUNNING_THREAD--; <span class="hljs-keyword">if</span><span class="hljs-number">0</span>){ <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span><span class="hljs-number">0</span><span class="hljs-number">3</span>; i++){ <span class="hljs-keyword">new</span><span class="hljs-string">".txt"</span>); f.<span class="hljs-keyword">delete</span>(); } }</code></pre></pre><strong><strong>Mobile version of the breakpoint continued multi-threaded Downloader</strong></strong> <ul> <ul> <li>Just paste the code directly here to use, remember when accessing the file path to change to the Android directory, add access to the network and external storage path</li> </ul> </ul><strong><strong>Show download progress with progress bar</strong></strong> <ul> <ul> <li>Set the maximum value of the progress bar when you get the total length of the download file</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs glsl"> <span class="hljs-comment">//设置进度条的最大值</span> pb.setMax(<span class="hljs-built_in">length</span>);</code></pre></pre> <ul> <ul> <li>The progress bar needs to show the overall download progress of three threads, so three threads each time they download, the length of the new download will be added to the progress bar<br> <ul> <li>Defines an int global variable that records the total download length of three threads</li> </ul></li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs"> <span class="hljs-keyword">int</span> progress;</code></pre></pre><pre><pre><code>* 刷新进度条</code></pre></pre><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs go"> while((<span class="hljs-built_in">len</span> = is.read(b)) !=<span class="hljs-number"> -1</span>){ raf.write(b,<span class="hljs-number"> 0</span><span class="hljs-built_in">len</span>); <span class="hljs-comment">//把当前线程本次下载的长度加到进度条里</span> <span class="hljs-built_in">len</span>; pb.setProgress(progress);</code></pre></pre> <ul> <ul> <li>Each time the breakpoint is downloaded, the download starts from the new starting position, and the progress bar is also displayed at the beginning of the new location, and the progress bar progress is also processed when the cache file is read to get a fresh download start Location.</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs"> <span class="hljs-keyword">new</span> FileInputStream(file); <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> InputStreamReader(fis)); String text = br.readLine(); <span class="hljs-keyword">int</span> newStartIndex = Integer.parseInt(text); <span class="hljs-comment">//新开始位置减去原本的开始位置,得到已经下载的数据长度</span> <span class="hljs-keyword">int</span> alreadyDownload = newStartIndex - startIndex; <span class="hljs-comment">//把已经下载的长度设置入进度条</span> progress += alreadyDownload;</code></pre></pre><strong><strong>Add a text box to show percent progress</strong></strong><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs avrasm"> tv<span class="hljs-preprocessor">.setText</span><span class="hljs-number">100</span> / pb<span class="hljs-preprocessor">.getMax</span><span class="hljs-string">"%"</span>)<span class="hljs-comment">;</span></code></pre></pre><strong><strong>Use of Httputils</strong></strong> <blockquote> <blockquote> <p>The httputils itself supports multi-threaded breakpoint continuation, which is very convenient to Use.</p> </blockquote> </blockquote> <ul> <ul> <li>Create a Httputils object</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs fix"><span class="hljs-attribute"> HttpUtils http </span>=<span class="hljs-string"> new HttpUtils();</span></code></pre></pre> <ul> <ul> <li>Download file</li> </ul> </ul><pre class="prettyprint"><code class=" hljs java">Http.download (url,<span class="hljs-comment"><span class="hljs-comment">//download the requested URL</span></span>Target<span class="hljs-comment"><span class="hljs-comment">//download Data Save path and file name</span></span> <span class="hljs-keyword"><span class="hljs-keyword">true</span></span>,<span class="hljs-comment"><span class="hljs-comment">//whether to open the breakpoint to continue transmission</span></span> <span class="hljs-keyword"><span class="hljs-keyword">true</span></span>,<span class="hljs-comment"><span class="hljs-comment">//if the server response header contains a file name, it is automatically renamed after the download is complete</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Requestcallback<file> () {<span class="hljs-comment"><span class="hljs-comment">//listen for download status</span></span> <span class="hljs-comment"><span class="hljs-comment">//download Successful This method call</span></span> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onsuccess</span></span>(responseinfo<file> Arg0) {tv.settext (<span class="hljs-string"><span class="hljs-string">"download succeeded"</span></span>+ Arg0.result.getPath ()); }<span class="hljs-comment"><span class="hljs-comment">//download failed This method call, such as the file has been downloaded, no network permissions, no access to the file, the method passed in a string parameter to tell the reason for failure</span></span> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onfailure</span></span>(httpexception arg0, String Arg1) {tv.settext (<span class="hljs-string"><span class="hljs-string">"download failed"</span></span>+ arg1); }<span class="hljs-comment"><span class="hljs-comment">//constant Call during the download process to refresh the progress bar</span></span> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onloading</span></span>(<span class="hljs-keyword"><span class="hljs-keyword">Long</span></span>Total<span class="hljs-keyword"><span class="hljs-keyword">Long</span></span>Current<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Isuploading) {<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>. onloading (total, current, isuploading);<span class="hljs-comment"><span class="hljs-comment">//set The total length of the progress bar</span></span>Pb.setmax ((<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>) total);<span class="hljs-comment"><span class="hljs-comment">//set progress bar Current Progress</span></span>Pb.setprogress ((<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>) (current); Tv_progress.settext (current *<span class="hljs-number"><span class="hljs-number"></span> -</span>/total +<span class="hljs-string"><span class="hljs-string">"%"</span></span>); } });</code></pre> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>"Android-011" "multi-threaded download"</p></p></span>

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.