Only 4 lines of code to implement Android fast file download _android

Source: Internet
Author: User

Written in front of the nonsense

Download files, almost all apps will use the function! Forget it, or no nonsense, directly open write it ...

Simple to use

Completion of a download task requires only 4 lines of code, what breakpoint continued, large file download, notice bar progress show .... You don't have to worry about it.

 Create a download task, DownloadURL is the download link
downloadmanager.request Request = new Downloadmanager.request (Uri.parse (downloadurl ));
Specify download path and download filename
request.setdestinationinexternalpublicdir ("/download/", filename);
Get the Download Manager
Downloadmanager downloadmanager= (Downloadmanager) Mcontext.getsystemservice (context.download_ SERVICE);
Add the download task to the download queue, otherwise it will not be downloaded
downloadmanager.enqueue (request); 

Advanced usage
----Through the above code you can also see that we are using the system provided by the download Manager to download, from API 9 began to support, so do not worry about compatibility issues
----since it is provided by the system, there is certainly a more powerful use, the article continues to

Let's look at Downloadmanager's source code and provide so many ways

The method of Downloadmanager

The method of Downloadmanager.request

The method is almost the same, has been compared to the whole, can meet most of our use of the scene.

Actual use
Let's take a look at the use of these methods in app update for example.

1. First, we'll comb through the updated logic in app apps.


Update in App Apps

2. Next look at the specific implementation, on the code

 Download private void downloadapk (String versionurl, String versionname) {//Create a download task using the System Downloader downloadmanager.request R
    Equest = new Downloadmanager.request (Uri.parse (Versionurl)); Request.setallowedoverroaming (false);//roaming network can download//set file type, you can automatically open the file after the download mimetypemap mimetypemap = Mimetypemap.
    Getsingleton ();
    String mimestring = mimetypemap.getmimetypefromextension (Mimetypemap.getfileextensionfromurl (VERSIONURL));

    Request.setmimetype (mimestring);
    displayed in the notification bar, the default is the display of request.setnotificationvisibility (DownloadManager.Request.VISIBILITY_VISIBLE);

    Request.setvisibleindownloadsui (TRUE);
    SDcard directory under the download folder, must be set Request.setdestinationinexternalpublicdir ("/download/", versionname); Request.setdestinationinexternalfilesdir (), you can also make your own download path//download request to join the download queue Downloadmanager = (Downloadmanager) mconte
    Xt.getsystemservice (Context.download_service); After joining the download queue, the task returns a long ID,//The ID can cancel the task, restart the task, and so on, see the above Source code box up Method Mtaskid = DownloadmanaGer.enqueue (Request); Registers the broadcast receiver, listens for download status Mcontext.registerreceiver (receiver, new Intentfilter (Downloadmanager.action_download_complete
  )); 
 }

Next up is the broadcast receiver.

   Broadcast receiver, receiving download status
  private Broadcastreceiver receiver = new Broadcastreceiver () {
    @Override public
    Void OnReceive (context context, Intent Intent) {
      checkdownloadstatus ()//Check download status
    }
  }; 

Check download status

 Check download status private void Checkdownloadstatus () {downloadmanager.query Query = new Downloadmanager.query ();
    Query.setfilterbyid (Mtaskid)//filter download task, incoming task ID, variable parameter Cursor c = downloadmanager.query (query);
      if (C.movetofirst ()) {int status = C.getint (C.getcolumnindex (downloadmanager.column_status));
        Switch (status) {case downloadmanager.status_paused:mlog.i (">>> download Paused");
        Case downloadmanager.status_pending:mlog.i (">>> download delay");
          Case DOWNLOADMANAGER.STATUS_RUNNING:MLOG.I (">>> is downloading");
        Break
          Case downloadmanager.status_successful mlog.i (">>> Download Complete"); Download Complete installation apk//downloadpath = Environment.getexternalstoragepublicdirectory (environment.directory_downloads). GetA
          Bsolutepath () + File.separator + versionname;
          installapk (New File (Downloadpath));
        Break Case DOWNLOADMANAGER.STATUS_FAILED:MLOG.I (">≫> download Failed ");
      Break 
 }
    }
  }

Install APK

   Perform installation
  protected void installapk (file file) {
    if (!file.exists ()
    ) return after downloading to local Intent Intent = new Intent (intent.action_view);
    Uri uri = uri.parse ("file://" + file.tostring ());
    Intent.setdataandtype (URI, "application/vnd.android.package-archive");
    Opening activity in service must be set FLAG, followed by explanation of
    intent.setflags (intent.flag_activity_new_task);
    Mcontext.startactivity (intent);
  } 

This completes the application to update the app's code, but there are some pits to pay attention to!

Hope you can see the last few words, or you will be in the pit!
1. Although the download does not need to worry about their own, but it is recommended to put the entire four pieces of code in service execution, because in the activity, when the user presses the home key, even if the download is finished, will not eject the installation interface
2. It is recommended to start the service in a startservice manner, so that it will not be bound to the activity lifecycle to ensure a smooth installation after downloading.
3.Service after use to stop in time!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.