Use the Downloadmanager provided by the Android system to download files _android

Source: Internet
Author: User
Tags stub

After android2.3, the Android system provides a system component that can be used by other app apps to download things that are easy to use.

For example, we can download the new version of the app apk while registering a broadcast receiver to receive the broadcast from Downloadmanager when the download is complete, and then automatically install the program.

The SDK joins the Downloadmanager service in API Level 9, which allows for long time downloads to be delivered to the system, completely managed by the system.

Look directly at the instance code:

Package com.hebaijun.downloadtest; 
Import java.io.UnsupportedEncodingException; 
 
Import Java.net.URLEncoder; 
Import android.app.Activity; 
Import Android.app.DownloadManager; 
Import Android.app.DownloadManager.Request; 
Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.content.IntentFilter; 
Import android.content.SharedPreferences; 
Import Android.database.Cursor; 
Import Android.net.Uri; 
Import Android.os.Bundle; 
Import Android.preference.PreferenceManager; 
Import Android.util.Log; 
 
Import Android.webkit.MimeTypeMap; 
  public class Downloadtestactivity extends activity {private Downloadmanager Downloadmanager; 
  Private Sharedpreferences prefs; 
  private static final String dl_id = "Downloadid"; /** called the activity is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); DOwnloadmanager = (Downloadmanager) getsystemservice (Download_service);  
  Prefs = Preferencemanager.getdefaultsharedpreferences (this); 
    @Override protected void OnPause () {//TODO auto-generated Method Stub super.onpause (); 
  Unregisterreceiver (receiver); 
    @Override protected void Onresume () {//TODO auto-generated Method Stub super.onresume (); 
      if (!prefs.contains (dl_id)) {String URL = "Http://10.0.2.2/android/film/G3.mp4";  
      Start Download Uri resource = Uri.parse (ENCODEGB (URL));  
      Downloadmanager.request Request = new Downloadmanager.request (Resource); Request.setallowednetworktypes (Request.network_mobile |  
      Request.network_wifi);  
      Request.setallowedoverroaming (FALSE); 
      Set File type Mimetypemap Mimetypemap = Mimetypemap.getsingleton (); 
      String mimestring = mimetypemap.getmimetypefromextension (mimetypemap.getfileextensionfromurl (URL)); 
      Request.setmimetype (mimestring); InThe notification bar displays request.setshowrunningnotification (true); 
      Request.setvisibleindownloadsui (TRUE); 
      SDcard Directory of the download folder Request.setdestinationinexternalpublicdir ("/download/", "G3.mp4");  
      Request.settitle ("Mobile G3 advertisement");  
      Long id = downloadmanager.enqueue (request);  
    Save ID Prefs.edit (). Putlong (dl_id, id). commit ();  
    else {//download already started, check status Querydownloadstatus (); 
  } registerreceiver (receiver, new Intentfilter (Downloadmanager.action_download_complete)); 
   /** * If the server does not support the Chinese path, the encoding of the URL needs to be converted. * @param String * @return/public string ENCODEGB (string string) {//Convert Chinese encoding string split[] = str 
    Ing.split ("/"); 
      for (int i = 1; i < split.length i++) {try {split[i] = Urlencoder.encode (split[i), "GB2312"); 
      catch (Unsupportedencodingexception e) {e.printstacktrace (); 
    } split[0] = split[0]+ "/" +split[i]; } Split[0] = SPLit[0].replaceall ("\\+", "%20");/processing space return split[0]; Private Broadcastreceiver receiver = new Broadcastreceiver () {@Override public void onreceive (Contex T context, Intent Intent) {//The download ID can be obtained here, so you can know which file download is complete. 
      Apply with multiple download tasks for listening log.v ("intent", "" "+intent.getlongextra (downloadmanager.extra_download_id, 0));  
    Querydownloadstatus ();  
   
  }  
  };  
    private void Querydownloadstatus () {downloadmanager.query Query = new Downloadmanager.query ();  
    Query.setfilterbyid (Prefs.getlong (dl_id, 0));  
    Cursor C = downloadmanager.query (query);  
      if (C.movetofirst ()) {int status = C.getint (C.getcolumnindex (downloadmanager.column_status)); 
      Switch (status) {case DOWNLOADMANAGER.STATUS_PAUSED:LOG.V ("Down", "status_paused"); 
      Case DOWNLOADMANAGER.STATUS_PENDING:LOG.V ("Down", "status_pending"); Case downloadmanager.status_running://is downloading, do not do anything log.v ("Down"," status_running ");  
      Break 
        Case downloadmanager.status_successful://Complete LOG.V ("Down", "Download Complete");  
      Break 
        Case downloadmanager.status_failed://Clear downloaded content, download log.v again ("Down", "status_failed");  
        Downloadmanager.remove (Prefs.getlong (dl_id, 0));  
        Prefs.edit (). Clear (). commit ();  
      Break 
 }  
    } 
  } 
}

The last required permissions are:

<uses-permission android:name= "Android.permission.INTERNET"/>
<uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>

If you need to hide the prompts and display of the download tool, modify the code:

Request.setshowrunningnotification (false);
Request.setvisibleindownloadsui (FALSE);

Add the following permissions:

<uses-permission android:name= "Android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>

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.