Download Files With WorkManager

QuestionsCategory: AndroidDownload Files With WorkManager
Ahsen Saeed Staff asked 11 months ago

Can we do download files with horizontal progressbar(like 30/100) update using WorkManager?

1 Answers
Best Answer
Kevin Mallone Staff answered 11 months ago

First of all WorkManager did not give us any kind method which we can use to push values time to time in our ViewModel or Activity. In your case the percentage value of total downloading. We can only observe the Worker by observing its WorkStatus or able to receive output data when the worker complete its execution, not when the Worker is currently executing.

But hours of spending I’m able to to give you a solution. To download the file we need to have a Worker which purpose is to download file. Below is the Worker.

public class DownloadWorker extends Worker {

   private LiveDataHelper liveDataHelper;

   public DownloadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
          super(context, workerParams);
          liveDataHelper = LiveDataHelper.getInstance();
   }

   @NonNull
   @Override
    public Result doWork() {
           try {
                 URL u = new URL("https://i.pinimg.com/originals/49/70/17/497017869c892b73b128ff72f2732035.jpg");
                 URLConnection c = u.openConnection();
                 c.connect();
                 int lengthOfFile = c.getContentLength();
                 InputStream in = c.getInputStream();

                 byte[] buffer = new byte[1024];
                 int len1;
                 long total = 0;
                 while ((len1 = in.read(buffer)) > 0) {
                        total += len1; //total = total + len1
                        int percent = (int) ((total * 100) / lengthOfFile);
                        liveDataHelper.updatePercentage(percent);
                 }
             } catch (Exception e) {
                  e.printStackTrace();
                  return Result.FAILURE;
            }
            return Result.SUCCESS;
     }
}

Now LiveDataHelper is the helper class which updates the Activity about how much percentage file is downloading. Rest of the code in doWork is for file downloading.

The following shows the LiveDataHelper class.

public class LiveDataHelper {

       private MediatorLiveData<Integer> _percent = new MediatorLiveData<>();

       private LiveDataHelper() {
       }

       private static LiveDataHelper liveDataHelper;

       synchronized public static LiveDataHelper getInstance() {
              if (liveDataHelper == null)
                     liveDataHelper = new LiveDataHelper();
              return liveDataHelper;
       }

       void updatePercentage(int percentage) {
             _percent.postValue(percentage);
       }

      LiveData<Integer> observePercentage() {
              return _percent;
      }
}

And finally in your Activity simply observe the data.

OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(DownloadWorker.class)
                  .build();
WorkManager.getInstance().enqueue(oneTimeWorkRequest);

LiveDataHelper.getInstance().observePercentage()
              .observe(this, new Observer<Integer>() {
                     @Override
                     public void onChanged(@Nullable Integer integer) {
                            // update your progressBar here.
                     }
               });

After en-queuing the Worker start observing the total downloading file percentage with LiveDataHelper class.

If this solution solves your problem then please close this issue…