SoFunction
Updated on 2025-03-02

Writing summary based on DownloadManager

I have always heard of Android's own DownloadManager, which is just procrastination and has no time to study. In fact, in many project developments, there is a function that is very important, that is, the application check and update! Based on DownloadManager, you can make a lightweight downloader and hand over the download tasks to the system to perform to reduce the pressure on your own APP. Why not do it? !

Basic usage posture of DownloadManager

Instantiation via getSystemService

DownloadManager downloadManager = (DownloadManager)(Context.DOWNLOAD_SERVICE);
Build download request

 request = new (("Target file download address"));
//Set the target folder, if you want to download a testDownload/test/ in the storage directory of the system("testDownload", "test/");
//Set the network environment required for download, and can be downloaded in both mobile network and WiFi environment (.NETWORK_MOBILE | .NETWORK_WIFI);//Notification bar settings//Show in the notification bar(.VISIBILITY_VISIBLE);

Notice! ! ! If you choose not to display in the notification bar, the following permissions must be declared

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

Then set it invisible

(.VISIBILITY_HIDDEN);

Otherwise, a securityException will be thrown

//Set the file type to apk type, and when the downloadManager calls openFile, the corresponding program will be called("application/");
 //Start download and get a unique downloadId, which is very usefullong downloadId = (request);

How to get the download situation

private int[] getBytesAndStatus(long downloadId) {

    //Build an array to store the downloaded file size, total size, and download status    int[] bytesAndStatus = new int[]{
        -1, -1, 0
    };
    //File query by building the downloadId obtained when download request     query = new ().setFilterById(downloadId);
    Cursor cursor = null;
    try {
      cursor = (query);
      if (cursor != null &amp;&amp; ()) {
        //The file size has been downloaded        bytesAndStatus[0] = ((DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        //Total size of downloaded file        bytesAndStatus[1] = ((DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        //Download Status        bytesAndStatus[2] = ((DownloadManager.COLUMN_STATUS));
      }
    } finally {
      if (cursor != null) {
        ();
      }
    }
    return bytesAndStatus;
  }

Register to listen to the broadcast of successful download of the file

private BroadcastReceiver downloadCompleteReceiver;
downloadCompleteReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        //When the file download is successful          query = new ();
        //Finish by downloaded id        (downloadId);
        Cursor c = (query);
        if (()) {
            int status = ((DownloadManager.COLUMN_STATUS));
            switch (status) {
              //Download completed              case DownloadManager.STATUS_SUCCESSFUL:

                 break;

               }

         }
      }
    };
//Register, here can only intercept the broadcast of successful file download, and cannot perform progress monitoring. Unsubscribe to the broadcast in an appropriate place.(downloadCompleteReceiver,
        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Many blogs on the Internet use custom ContentObserver to obtain local file changes. In fact, you can find a different way. Calling the above getBytesAndStatus(long downloadId) through a timer interval can achieve the same effect. Use Rxjava to implement a simple timer.

/**
  * Since DownloadManager itself does not provide a API for real-time progress, the downloaded file size is obtained through the following timer
  */
  private void updateProgress() {
        //Refresh the progress every 0.5 seconds, remember to log out in the appropriate place.        Disposable timeDisposable = (500, ).subscribeOn(())
        .observeOn(()).subscribe(new DataConsumer&lt;Long&gt;() {
          @Override
          public void acceptData(@ Long aLong) {

            int [ ] bytesAndStatus = getBytesAndStatus(downloadId);
            //Todo can just do a callback here          }
        });

  }

After understanding the basic usage of DownloadManager, then use it to encapsulate a simple and easy-to-use downloader!

Realize the effect

  builder = new (this).title("Download Notification")
          .description("Downloading new version V1.2.0")
          .downloadUrl("/upload/connAssitantDownload/upload/MobileAssistant_1.apk")
          .fileSaveName("MobileAssistant_1.apk").fileSavePath("testDownload")
          .notifyVisible(true)
          .fileType().apkInstallHint(true).onProgressListener(new () {
            @Override
            public void onProgress(int downloadedSize, int totalSize) {

              int progress =(int)((downloadedSize*1.0f/totalSize)*100);
              ("progress=%d",progress);
               //Progress callback
            }

            @Override
            public void onSuccess(Uri fileUri) {
             //Uri with successful callback from file download 

            }

            @Override
            public void onFail() {
             //File download failed  

            }

            @Override
            public void fileAlreadyExits(File file) { 
            // When you want to download the same file repeatedly, locally check whether the same file exists and make a callback             
            }
          });
      DownloadHelper downloadHelper = ();
      //Start download      ();
      //Remove the download task      ();

Please go to the source code/yuwenque/