SoFunction
Updated on 2025-03-02

Use the DownloadManager provided by Android to download files

After Android 2.3, android system provides a system component for other apps to download things, which is very convenient to use.

For example, we can use it to download the new version of the app, and register a broadcast receiver at the same time to receive the broadcast sent by the DownloadManager when the download is completed, and then automatically install the program.

The SDK has added the DownloadManager service to API Level 9, which can hand over long-term download tasks to the system and is completely managed by the system.

Look directly at the example code:

package ; 
 
import ; 
import ; 
 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
public class DownloadTestActivity extends Activity { 
  private DownloadManager downloadManager; 
  private SharedPreferences prefs; 
  private static final String DL_ID = "downloadId"; 
  /** Called when the activity is first created. */ 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    (savedInstanceState); 
    setContentView(); 
    downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); 
    prefs = (this);  
  } 
  @Override 
  protected void onPause() { 
    // TODO Auto-generated method stub 
    (); 
    unregisterReceiver(receiver); 
  } 
  @Override 
  protected void onResume() { 
    // TODO Auto-generated method stub 
    (); 
    if(!(DL_ID)) {  
      String url = "http://10.0.2.2/android/film/G3.mp4"; 
      //Start download      Uri resource = (encodeGB(url));  
       request = new (resource);  
      (Request.NETWORK_MOBILE | Request.NETWORK_WIFI);  
      (false);  
      //Set file type      MimeTypeMap mimeTypeMap = (); 
      String mimeString = ((url)); 
      (mimeString); 
      //Show in the notification bar      (true); 
      (true); 
      //The download folder in the sdcard directory      ("/download/", "G3.mp4"); 
      ("Mobile G3 Advertising");  
      long id = (request);  
      //Save id      ().putLong(DL_ID, id).commit();  
    } else {  
      //Download has started, check the status      queryDownloadStatus();  
    }  
 
    registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
  } 
   
  /**
    * If the server does not support Chinese path, it is necessary to convert the encoding of the url. 
    * @param string
    * @return
    */ 
  public String encodeGB(String string) 
  { 
    //Convert Chinese encoding    String split[] = ("/"); 
    for (int i = 1; i < ; i++) { 
      try { 
        split[i] = (split[i], "GB2312"); 
      } catch (UnsupportedEncodingException e) { 
        (); 
      } 
      split[0] = split[0]+"/"+split[i]; 
    } 
    split[0] = split[0].replaceAll("\\+", "%20");//Processing spaces    return split[0]; 
  } 
   
  private BroadcastReceiver receiver = new BroadcastReceiver() {  
    @Override  
    public void onReceive(Context context, Intent intent) {  
      //The downloaded id can be obtained here, so that you can know which file has been downloaded.  Suitable for listening with multiple download tasks      ("intent", ""+(DownloadManager.EXTRA_DOWNLOAD_ID, 0)); 
      queryDownloadStatus();  
    }  
  };  
   
  private void queryDownloadStatus() {  
     query = new ();  
    ((DL_ID, 0));  
    Cursor c = (query);  
    if(()) {  
      int status = ((DownloadManager.COLUMN_STATUS));  
      switch(status) {  
      case DownloadManager.STATUS_PAUSED:  
        ("down", "STATUS_PAUSED"); 
      case DownloadManager.STATUS_PENDING:  
        ("down", "STATUS_PENDING"); 
      case DownloadManager.STATUS_RUNNING:  
        //Downloading, don't do anything        ("down", "STATUS_RUNNING"); 
        break;  
      case DownloadManager.STATUS_SUCCESSFUL:  
        //Finish        ("down", "Download Completed"); 
        break;  
      case DownloadManager.STATUS_FAILED:  
        //Clear the downloaded content and download it again        ("down", "STATUS_FAILED"); 
        ((DL_ID, 0));  
        ().clear().commit();  
        break;  
      }  
    } 
  } 
} 

The last permissions required are:

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

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

(false);
(false);

Add the following permissions:

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

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.