Android Breakpoint Renew Download file

Source: Internet
Author: User
Tags response code sqlite sqlite database stub

There are two functional points here.
1, download
2, download After the pause can be downloaded in the location.

So the tentative technology involved is that HTTP network requests, multithreading, SQLite database cache Download Locations.

Process flow of code flow: Fires the download behavior from the main activity button. Delegate Downloadtask the child thread to manage the download transaction. Downloadtask Call the Downloader filedownlodered complete the download file. Filedownlodered calls multiple Downloadthread threads (multithreading) to download file blocks from the server. Downloadthread downloads the current thread to the SQLite database, recording the download location. Download from the pause position immediately after the pause.
Activity->downloadtask->filedownlodered->downloadthread->db;
Button Event response code for the main activity

    @Override public void OnClick (View v) {//TODO auto-generated Method stub switch (v).
                GetId ()) {case r.id.startdownload:string path = Pathtext.gettext (). toString ();//Get Download path
                    if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {
                    When the SD card exists//getexternalstorgedirectory (); File savefile = environment. Getexternalstoragepublicdirectory (environment.directory_documents
                            ); Gets the text directory to the SD card.
                    It is also the absolute address of the directory where we download the files.
Getexternalfilesdir (environment.directory_documents); Download (path, savefile),//Based on resource path, and files are stored locally in the directory address as parameters of the download file try {log.i TAG,
                        path);
                    LOG.I (TAG, Savefile.getcanonicalpath (). toString ()); catch (IOException e) {// TODO auto-generated Catch block E.printstacktrace ();
                LOG.I (TAG, "SD card exists, start downloading");
                else {log.e (TAG, Getresources (). getString (R.string.sdcarderror));
                } downloadbutton.setenabled (FALSE);
                Stopbutton.setenabled (TRUE);

            Break
                Case R.id.stopdownload:exit ();
                Downloadbutton.setenabled (TRUE);
                Stopbutton.setenabled (FALSE);
            Break
            Default:break; }//This is the logic of the download method, entrusted to the Downloadtask child thread for download management.
The UI thread cannot be used for deferred operations. public void Download (String path, File savedir) {//TODO auto-generated method Stub task = new DOWNLOADTA
        SK (path, savedir);
    New Thread (Task). Start (); }

The following is the management logic for the download task by the Downloadtask child thread. It is also delegated to the Filedownlodered class for the actual download operation. The main function of this class is to create a new download task and implement the feedback processing of the filedownlodered download class callback.

Private class Downloadtask implements Runnable {private final String path;
        Private final File Savedir;

        Private filedownlodered Filedownloader;
            Public Downloadtask (String path, File savedir) {this.path = path;

        This.savedir = Savedir;
            public void exit () {if (Filedownloader!= null) {filedownloader.exit ();
        }///download task contains a download listener. Downloadprocesslistener Downloadprocesslistener = new Downloadprocesslistener () {//  This listener listens to download progress information from the filedownlodered of the downloader and then updates the UI via handler @Override public void ondownloadsize (int
                Downloadsize) {//TODO auto-generated method Stub: msg = new Message ();
                Msg.what = processing;
                Msg.getdata (). Putint ("size", downloadsize);
            Uihandler.sendmessage (msg);

        }
        }; @Override public void RUn () {//TODO auto-generated Method Stub try {//New one downloader, download must
                It has to be put here, in the constructor because the delay operation of designing to the network request may report the UI thread latency exception.
                Filedownloader = new filedownlodered (Getapplicationcontext (), Path, Savedir, 8);

                Progressbar.setmax (Filedownloader.getfilesize ());
                LOG.I (TAG, Thread.CurrentThread (). GetName () + "go to download"); Download begins downloading log.i (TAG, string.valueof (filedownloader. Download) (Downloadprocessliste
NER)));
                This download method is the way the downloader actually performs the download function,//} catch (Exception e) {//Todo:handle Exception
                E.printstacktrace ();

            Uihandler.sendmessage (Uihandler.obtainmessage (failure)); }
        }
    }

Filedownlodered Download Method
The main function of this method is to

public int Download (Downloadprocesslistener listener) {try {randomaccessfile randout = new RANDOMACC

            Essfile (This.savefile, "RWD");
            if (this.filesize > 0) randout.setlength (this.filesize);
            Randout.close ();
            URL url = new URL (this.downloadurl); If the data map does not contain the same number of records as the number of threads.
            Then the same download operation, the data record//the number to clear zero.
                if (This.data.size ()!= this.threads.length) {this.data.clear ();
                for (int i = 0; i < this.threads.length i++) this.data.put (i + 1, 0);

            this.downloadsize = 0;
            LOG.I (TAG, "data Length" + string.valueof (This.data.size ()));
                for (int i = 0; i < this.threads.length i++) {int downloadedlength = This.data.get (i + 1); if (Downloadedlength < This.block && This.downloadsize < This.filesize) {//Table name the task of this thread has not started this.threads[i] = new Downloadthread (this, URL,
                    This.savefile, This.block, This.data.get (i + 1), i + 1);                 This.threads[i].setpriority (7);

                This.threads[i].start (); } else {This.threads[i] = null;//indicates that the thread has completed the download task} Fileservice
            . Delete (This.downloadurl);
            Fileservice.save (This.downloadurl, this.data);
            Boolean notfinished = true;
                while (notfinished) {thread.sleep (90);
                Notfinished = false;
                            for (int i = 0; i < this.threads.length i++) {if (this.threads[i)!= null//Enter when none of the threads have finished downloading.
                        &&!this.threads[i].isfinished ()) {notfinished = true; if (This.threads[i].getdownloadedlength () = = 1) {//determine if each thread has failed, if a failed restart download this.threads[i] = new D
                                    Ownloadthread (this, URL, This.savefile, This.block,
                            This.data.get (i + 1), i + 1);
                            This.threads[i].setpriority (7);
                        This.threads[i].start (); }} if (Listener!= null) listener.ondownloadsiz
            E (this.downloadsize);
                } if (downloadsize = = this.filesize)//If the downloaded file size is the same as the size of the resource obtained from the HTTP header, the download is complete.
                Then delete the information that is logged by all threads.
        This.fileService.delete (This.downloadurl);
        catch (FileNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } CATCH (interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
    return this.downloadsize; }

The

Downloadthread Run method is directly httpconnection to the remote server, and then uses the Randomaccessfile class for multi-threaded downloads of classes that can randomly access the overwriting file.

    @Override public void Run () {//TODO auto-generated Method Stub//each thread downloads each piece of information. if (Downloadedlength < block) {try {//Create a new Httpurl link httpurlconnection connection = (HTTPU
                rlconnection) Downurl. OpenConnection ();
                Connection.setconnecttimeout (5 * 1000);
                Connection.setrequestmethod ("get");
                                Connection. Setrequestproperty ("Accept"),
                                        "Image/gif, Image/jpeg,image/pjpeg,image/pjpeg,application/x-shockwave-flash,"
                                        + "Application/xaml+xml, Application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP, Application/x-ms-application,"
                + "application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");
             Connection.setrequestproperty ("Accept-language", "ZH-CN");   Connection.setrequestproperty ("Charset", "UTF-8");
                int startpos = block * (threadId-1) + downloadedlength;//calculates the start and end position of the download itself within each thread.
    int endpos = block * THREADID-1;           Use the Range field of the HTTP protocol to set the location of the download.
                Connection.setrequestproperty ("Range", "bytes=" + startpos + "-" + endpos);

                Connection.setrequestproperty ("Connection", "keep-alive");
                InputStream instream = Connection.getinputstream ();
                byte[] buffer = new byte[1024];
                int length = 0;
                Print ("Thread:" + This.threadid + "start to download from position:\t" + startpos);
                Randomaccessfile threadfile = new Randomaccessfile (This.savefile, "RWD");
                Threadfile.seek (startpos);
    while (!this.downloader.getexited () && (length = instream.read (buffer, 0, 1024))!=-1) {Determining condition: Whether the pause signal is given according to Downloader.getexited () and whether the current download block is at the end of the stream.
                    Threadfile.write (buffer, 0, length);
                    downloadedlength = length;
                    Downloader.update (This.threadid, this.downloadedlength),//update download data to the SQLite database, used to resume the download location after pausing.
                Downloader.append (length);
                } threadfile.close ();
                Instream.close ();
                if (downloader.getexited ()) Print ("Thread:" + This.threadid + "has been paused.");

                else//If the downloader is not paused, Print ("Thread:" + this.threadid + "Download Finish");

            this.finished = true;//Whether the download is complete or is used to interrupt the download, all the information to download. catch (Exception e) {//Link remote resource failure,//todo:handle Exception this.downloadedlength =-1
                ;
            Print ("Thread:" + This.threadid + ":" + e.tostring ());
 }
        }
    }
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.