Android Class Filedownloadlist Analysis _android

Source: Internet
Author: User
Tags save file

Code First, then analyze

public class Filedownloadlist {/** contexts/private context mcontext;
 /** Request Object * * Private baserequestlims filerequest = null;
 /** Progress Bar dialog box */private Alertdialog progressdialog = null;
 /** progress bar control variable * * Private ProgressBar mprogress;
 
 /** percent Display control/private TextView mprogresspercent;
 Private File LocalFile = null;
 /** receive Httphelper to send the file size after the broadcast, to determine the size of the file * * Private downloadreceiver receiver;
 /** File Size * * Private long filelength = -1l;
 /** whether the broadcast flag is registered/private Boolean castflag = false;
 /** whether to show the progress bar logo */private Boolean showdialog = false;
 
 /** file Download the callback interface/private Runnable mcallback = null; Private Handler Mhandler = new Handler () {@Override public void Handlemessage (msg) {Super.handlemessage (ms
   g);
   int tempsize = (int) localfile.length (); if (Tempsize < filelength) {//File download if (ShowDialog) {//Show progress bar, update progress bar int progress = (int) (Double.va
          Lueof (tempsize)/double.valueof (filelength)) * 100);
          Mprogress.setprogress (tempsize); MprogResspercent.settext (Progress + "%");
      }else{///download file completed if (Castflag) {//If registered broadcast, cancellation broadcast mcontext.unregisterreceiver (receiver);  
    Castflag = false;
     } if (ShowDialog) {mprogress.setprogress (int) filelength);
     Mprogresspercent.settext ("100%");
    Progressdialog.dismiss ();
      } if (Mcallback!= null) {try{thread.sleep (500);
     Mcallback.run ();
     }catch (Exception e) {e.printstacktrace ();
 
 }
    }
   }
  }
 }; /** * Constructor * @param activity//** * constructor * @param activity * @param showdialog Show progress bar logo/public Filedow
  Nloadlist (Context Context, Boolean ShowDialog) {mcontext = context;
  This.showdialog = ShowDialog;
  Filerequest = new Baserequestlims (Context,clientservicetype.file_down);
  Filerequest.setmethodtype (Baserequestlims.method_type_post);
    
 Filerequest.setcontext (Mcontext);
 Public Baserequestlims Getfilerequest () {return filerequest; /** * Download files by association type * @pAram FileName File name or file relative path on the server plus name * @param savedir saved in the local file directory * @param savename saved locally file name * @param GLLX Association type * @ PARAM callback processing thread after download/public void DownloadFile (string fileName, String Savedir, String savename, Runnable callback
  {if (callback!= null) {mcallback = callback;
  
  } File Savedirfile = new file (Savedir);
  Judge the Save Dir path exist or not if (!savedirfile.exists ()) {savedirfile.mkdirs ();
  
  } LocalFile = new File (savedir,savename); if (Localfile.isdirectory ()) {new Alertdialog.builder (Mcontext). Settitle ("hint"). Setmessage ("The Save file is directory
   "). Show ();
  Return
  } if (Filerequest.getservicetype () ==null) {filerequest.setservicetype (Clientservicetype.file_down);
  } filerequest.addparameter ("Fpath", fileName);
  Filerequest.addparameter ("FName", savename);
  Filerequest.setstreampath (Localfile.getabsolutepath ());
  Filerequest.setstream (TRUE); if (localfile.exists ()) {if (localfile.length () = 0) {Invokefile (Filerequest);
    }else{//file exists directly open if (ShowDialog) Buildprogressdialog (). Show ();
   Mhandler.sendmessage (Mhandler.obtainmessage ());
  }}else{Invokefile (filerequest); /** * Enter file download child thread * @param request/private void Invokefile (final baserequestlims request) {try{if (sh
   Owdialog) {Buildprogressdialog (). Show ();
   } receiver = new Downloadreceiver ();
   Intentfilter filter = new Intentfilter ();
   Filter.addaction ("Save_download_file");
   Mcontext.registerreceiver (receiver, filter);
   Castflag = true;
     The downloaded child thread new thread () {@Override public void run () {super.run ();
    Httphelper.invoke (Request);
  }}.start ();
  }catch (Exception e) {e.printstacktrace (); /** * Create Progress dialog box * @return * * Private Alertdialog Buildprogressdialog () {Alertdialog.builder Builder = new B
  Uilder (Mcontext);
  Builder.settitle ("Downloading files, please wait ...");
  Relativelayout container = new Relativelayout (mcontext); mprogress = new PrOgressbar (Mcontext);
  Mprogress.setid ("Progress". Hashcode ());
  Beanutils.setfieldvalue (mprogress, "Monlyindeterminate", Boolean.valueof (false));
  Mprogress.setindeterminate (FALSE); Layerdrawable layerdrawable = (layerdrawable) mcontext.getresources (). Getdrawable (Android.
  R.drawable.progress_horizontal);
  Clipdrawable clipdrawable = (clipdrawable) layerdrawable.getdrawable (2);
  Clipdrawable.setcolorfilter (Color.parsecolor ("#32B5E5"), mode.src_in);
  Mprogress.setprogressdrawable (layerdrawable);
  Mprogress.setpadding (0, 0, 0, 0); Mprogress.setindeterminatedrawable (Mcontext.getresources (). Getdrawable (Android).
  R.drawable.progress_indeterminate_horizontal));
  Mprogresspercent = new TextView (mcontext);
  Mprogresspercent.setid ("percent". Hashcode ());
  Mprogresspercent.settext ("0%");
  
  Mprogresspercent.settextsize (18);
  int containerpadding = dimensionutils.dip2px (Mcontext, 10);
  
Container.setpadding (containerpadding, containerpadding, containerpadding, containerpadding);  Layoutparams progresslayoutparams = new Layoutparams (layoutparams.match_parent, dimensionutils.dip2px (MContext, 4))
  ;
  Progresslayoutparams.addrule (relativelayout.center_vertical);
  Progresslayoutparams.addrule (relativelayout.left_of, Mprogresspercent.getid ());
  
  Mprogress.setlayoutparams (Progresslayoutparams);
  Layoutparams percentlayoutparams = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content);
  Percentlayoutparams.addrule (Relativelayout.align_parent_right);
  Percentlayoutparams.addrule (relativelayout.center_vertical);
  
  Mprogresspercent.setlayoutparams (Percentlayoutparams);
  Container.addview (mprogresspercent);
  Container.addview (mprogress);
  Builder.setview (container); Builder.setnegativebutton ("Cancel", new Onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int w
   Hich) {Dialog.dismiss ();
  
  }
  });
  ProgressDialog = Builder.create ();
 return progressdialog; Class Downloadreceiver extends Broadcastreceiver{@Override public void onreceive (context context, Intent Intent) {//Show progress bar filelength = Intent.getl
   Ongextra ("File_length",-1);
   if (ShowDialog) {mprogress.setmax (int) filelength);
     //Update the thread of the progress bar New threads () {@Override public void run () {super.run ();
      while (true) {try{thread.sleep (500);
      }catch (Exception e) {e.printstacktrace ();
      } mhandler.sendmessage (Mhandler.obtainmessage ());
      Gets the size of the download file int loadedsize = (int) localfile.length ();
      if (loadedsize >= filelength) {break;
  }}}.start ();
 } public Downloadreceiver Getreciver () {return receiver;
 }
}

It's logic:

Once you create a Filedownloadlist object, you can use the following methods directly to implement the download function.

DownloadFile (String fileName, String Savedir, String savename, Runnable callback)

That's what it means to realize:

1. In the current context, open the download thread. When you get to the size of the file you want to download, send a broadcast over it (this part is not shown in the above code).

2. In the current context, register a broadcast listener and listen for broadcasts that are identified as save_download_file. After hearing the broadcast for the first time, the first sent broadcast, which contains the size information for the file to be downloaded, detects the size of the local file every 5 milliseconds until the local file size (loadedsize) is greater than the size of the file (Filelength) to be downloaded, exiting the loop.

In the process of continuous detection, through Mhandler.sendmessage (Mhandler.obtainmessage ()); To have the UI thread update the progress bar.

The download thread keeps the stream of data returned by the server to the local file, so the size of the local file changes until it is equal to the size of the file being downloaded, and then exits the thread that is constantly detecting the size of the local file.

Other content not shown in the above code (in other parts of the code):

1. In the Invokefile (final Baserequestlims request) method, a download thread is opened as follows. The download thread writes the stream of files returned by the server to the local file (LocalFile); It also sends a SAVE_DOWNLOAD broadcast that contains information about the file size filelength to download the file.

The downloaded child thread
   new thread () {
    @Override public
    void Run () {
     super.run ();
     Httphelper.invoke (request);
   Start ();

The problem with the above code:

1. Context, the use of an activity, if the system calls the activity of the OnDestroy (), the download thread has not completed, it means that the size of the loadedsize or less than filelength. Thus, the thread that constantly detects the size of the local file is executing.

That is, the thread that detects the local file size and the download thread is still executing:

The thread that detects the local file size:

New Thread () {
    @Override public
    void Run () {
     super.run ();
     while (true) {
      try{
       thread.sleep;
      } catch (Exception e) {
       e.printstacktrace ();
      }
      Mhandler.sendmessage (Mhandler.obtainmessage ());
      Gets the size of the download file
      int loadedsize = (int) localfile.length ();
      if (loadedsize >= filelength) {break;}}}}
   . Start ();

Download Thread:

New Thread () {
        @Override public
        void Run () {
          super.run ();
          Httphelper.invoke (request);
      Start ();

So what's going to happen?

1. What I can be sure of is that there is a leak in the mcontext.

2). Downloadreceiver cannot be unregistered normally.

Analysis, to be continued.

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.