How to download File using Android WorkManager

In this android programming source code example, we are going to download File using Android WorkManager.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to download File using Android WorkManager

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"  tools:context=".WorkManagerAndJobSchedule.WorkManagerAndJobScheduleActivity1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ProgressBar
                android:id="@+id/progress_bar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/Widget.AppCompat.ProgressBar.Horizontal"
                android:max="100"
                android:progress="0"
                android:layout_gravity="center_vertical"/>

            <TextView
                android:id="@+id/progress_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="0/100"
                android:textColor="@color/colorPrimary"
                android:layout_gravity="center_horizontal"/>
        </LinearLayout>

        <Button
            android:id="@+id/download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@color/colorAccent"
            android:text="Download"
            android:textAllCaps="false"
            android:textColor="#ffffff"
            android:textSize="19sp" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class WorkManagerAndJobScheduleActivity1 extends AppCompatActivity {
    private Button downloadBtn;
    private ProgressBar progressBar;
    private TextView progress_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_manager_and_job_schedule1);
        downloadBtn = (Button) findViewById(R.id.download);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        progress_tv = (TextView) findViewById(R.id.progress_tv);
        downloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWork();
            }
        });
    }

    private void startWork(){
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresStorageNotLow(true)
                .build();
        OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(DownloadWorker.class)
                .setConstraints(constraints).build();;
        WorkManager.getInstance(this).enqueue(oneTimeWorkRequest);
        LiveDataHelper.getInstance().observePercentage().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                progressBar.setProgress(integer);
                progress_tv.setText(integer+"/100");
            }
        });
    }
}

DownloadWorker.java

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

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{
            File outputFile = new File(Environment.getExternalStorageDirectory(), "inducesmile.png");
            URL url = new URL("https://inducesmile.com/wp-content/uploads/2019/01/inducesmilelog.png");
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            int fileLength = urlConnection.getContentLength();
            FileOutputStream fos = new FileOutputStream(outputFile);
            InputStream inputStream = urlConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int len1;
            long total = 0;
            while ((len1 = inputStream.read(buffer))>0){
                total += len1;
                int percentage = (int) ((total * 100)/ fileLength);
                liveDataHelper.updateDownloadPer(percentage);
                fos.write(buffer, 0, len1);
            }
            fos.close();
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure();
        }
        return Result.success();
    }
}

LiveDataHelper.java

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;

public class LiveDataHelper{
    private LiveDataHelper(){}
    private static LiveDataHelper liveDataHelper;
    private MediatorLiveData<Integer> downloadPercent = new MediatorLiveData<>();

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

    public void updateDownloadPer(int percentage){
        downloadPercent.postValue(percentage);
    }

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

}

app/build.gradle

implementation 'androidx.work:work-runtime:2.1.0-beta02'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment