Multi-Threaded Download server-side picture resources

Source: Internet
Author: User

Service side situation is: Http://192.168.1.105:8080:/web/sky.jpg hit enter, in the browser display image resources >>>>>>> service-side code omitted ....

Down_activity.xml (button is to submit a Web request to download the picture, TextView is the interface prompt when the download is completed)

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <textview        android:id= "@+id/textview" android:layout_width= "Wrap_        Content "        android:layout_height=" wrap_content "/>    <button        android:id=" @+id/button "        Android : layout_width= "wrap_content"        android:layout_height= "wrap_content"        android:text= "Download"/></ Linearlayout>

Downloadactivity

Package Com.lw.http01;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.view.view;import Android.widget.button;import Android.widget.textview;public class DownLoadActivity extends Activity {private TextView textview;private Button button;private int count = 0;private Handler Handler = new Handler () {p ublic void Handlemessage (Android.os.Message msg) {int result = Msg.what;count + = result;if (count = = 3) {//Complete download Update UI interface can be T Extview.settext ("Download Success");};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( r.layout.down_activity) TextView = (TextView) Findviewbyid (r.id.textview); button = (button) Findviewbyid (R.id.button ); Button.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {/** * Gets the network picture in the child thread */new Thread () {public void run () {DownLoad load = new DownLoad (handler); Load.downloadfile ("http://192.168.1.105:8080:/web/ Sky.jpg ");};}. Start ();}});}}

DownLoad

Package Com.lw.http01;import Java.io.file;import Java.io.inputstream;import java.io.randomaccessfile;import Java.net.httpurlconnection;import Java.net.url;import Java.util.concurrent.executor;import Java.util.concurrent.executors;import Android.os.environment;import Android.os.handler;import android.os.Message; public class DownLoad {/** * Creates a thread pool of 3 threads */private Executor threadPool = Executors.newfixedthreadpool (3); static class downl Oadrunnable implements Runnable {/** * Defines the parameters passed over */private string url;private string filename;private long start;private l  Ong end;private Handler handler;public downloadrunnable (string url, String fileName, long Start,long end, Handler Handler) {super (); This.url = Url;this.filename = Filename;this.start = Start;this.end = End;this.handler = handler;} @Overridepublic void Run () {try {//Create URL address, and set the value URL httpurl = new URL (URL); HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); conn.setreadtimeout (5000); Conn.setrequestmethod ("GET");//HTTP protocol. PleaseSpecifies the length of the stream information Conn.setrequestproperty ("Range", "bytes=" + Start + "-" + end);//Locate write information to the specified file folder randomaccessfile access = new Ra Ndomaccessfile (FileName), "RWD");//To Snap to start point--position the file record pointer to the POS location. Access.seek (start);//Get input path. Get files from server InputStream in = Conn.getinputstream (); byte[] B = new byte[1024 * 4];int len = 0;while (len = In.read (b))! =- 1) {//Output access.write (b, 0, Len);} if (access! = NULL) {Access.close ();} if (in = null) {In.close ();} After each thread completes the download, the message is sent with a msg = new message (); message.what = 1;handler.sendmessage (message);} The catch (Exception e) {}}}/** * definition handler is due to the need for handler to send messages in downloadrunnable (each thread completes the download send message. Update main interface) */private Handler handler;public DownLoad (Handler Handler) {this.handler = Handler;} public void downLoadFile (String url) {try {/** * * creates URL address information. and set the number of parameters */url Httpurl = new URL (URL); HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); conn.setreadtimeout (5000); Conn.setrequestmethod ("get");//Get the overall size of the network resource int count = Conn.getcontentlength ();//Download each downloadthe size int block = count/3;//Gets the suffix name of the network resource string filename = getFile (URL);//Gets the folder root Folder file Parent = Environment.getexternalsto  Ragedirectory ();//Gets the true absolute path of the file DownLoadFile = new (parent, fileName);/** * 11 Overall Size/3 Blcok for 3 + 2 first thread 0-2 second thread 3-5 Third thread 6-10 */for (int i = 0; i < 3; i++) {Long start = i * block;long end = (i + 1) * BLOCK-1;IF (i = = 2) {end = Cou NT;} /** * Delivery start, end is due to Setrequestproperty because the protocol requires these 2 parameters * URL is because each thread download requires URL address information hander is sending a message. Update UI interface */downloadrunnable runnable = new Downloadrunnable (Url,downloadfile.getabsolutepath (), start, end, Handler); Threadpool.execute (runnable);}} catch (Exception e) {}}//Gets the file's suffix name by URL, public string getFile (string url) {return url.substring (Url.lastindexof ("/") + 1) ;}}


Multi-Threaded Download server-side picture resources

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.