PRDownloader library is a file downloader library for android. It comes with pause and resumes support while downloading a file. This library is capable of downloading large files from the internet and can download any type of file like image, video, pdf, apk and etc. It provides many features that can help a user to download files from the internet easily and efficiently. With this library, you can also check the status of the downloading using the download id and can perform many other important operations using the download id. This library contains many important methods that give full control to the user to handle the downloading states of the file like pause, cancel, resume, etc. You can make the following Requests with this library:
Pause a download request:
PRDownloader.pause(downloadId);
Cancel a download request:
// Cancel with the download id PRDownloader.cancel(downloadId); // The tag can be set to any request and then can be used to cancel the request PRDownloader.cancel(TAG); // Cancel all the requests PRDownloader.cancelAll();
Resume a download request:
PRDownloader.resume(downloadId);
Get status of a download request:
Status status = PRDownloader.getStatus(downloadId);
What we are going to build in this article?
A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step By Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Then Enter your App Name in the Name field and select Java from the Language drop-down menu.
Step 2: Add dependency
To add the dependency navigate to app > Gradle Scripts > gradle.build(Module: app) and add the below dependency in the dependencies section. After adding the dependency sync your project.
implementation 'com.mindorks.android:prdownloader:0.6.0'
Step 3: Add Internet Permission
Navigate to app > manifest > AndroidManifest.xml and add the internet permission.
<uses-permission android:name="android.permission.INTERNET"/>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
<!-- EditText to take the url from the user -->
< EditText
android:id = "@+id/url_etText"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "10dp"
android:hint = "@string/type_or_paste_your_url_here" />
<!-- Button to start downloading from file -->
< Button
android:id = "@+id/btn_download"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@+id/url_etText"
android:layout_centerHorizontal = "true"
android:text = "@string/download" />
<!-- linear layout that contains widgets to show information -->
< LinearLayout
android:id = "@+id/details_box"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@+id/btn_download"
android:layout_margin = "10dp"
android:layout_marginTop = "20dp"
android:background = "@drawable/box_design_layout"
android:orientation = "vertical"
android:padding = "10dp"
android:visibility = "gone" >
<!-- Textview to show the file name -->
< TextView
android:id = "@+id/file_name"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/click_on_start_button_to_start_downloading"
android:textSize = "20sp"
android:textStyle = "bold" />
<!-- progress bar to show the progress of downloading -->
< ProgressBar
android:id = "@+id/progress_horizontal"
style = "@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginLeft = "4dp"
android:layout_marginRight = "4dp"
android:progressTint = "@color/purple_200"
tools:ignore = "UnusedAttribute" />
<!-- textview to show the downloading percentage -->
< TextView
android:id = "@+id/downloading_percentage"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center_horizontal"
android:textAlignment = "center"
android:textSize = "12sp"
android:textStyle = "bold" />
<!-- this linear layout contains buttons -->
< LinearLayout
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center_horizontal"
android:orientation = "horizontal"
android:padding = "10dp" >
<!-- button to start the downloading -->
< Button
android:id = "@+id/btn_start"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/start" />
<!-- button to cancel or stop the downloading -->
< Button
android:id = "@+id/btn_stop"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "@string/stop" />
</ LinearLayout >
</ LinearLayout >
<!-- this textview will show the path where
the downloaded file is stored -->
< TextView
android:id = "@+id/txt_url"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@+id/details_box"
android:layout_marginTop = "10dp"
android:textSize = "15sp"
android:textStyle = "bold" />
</ RelativeLayout >
|
Below is the code for the Strings.xml file
< resources >
< string name = "app_name" >GFG PRDownloader Library</ string >
< string name = "download" >DOWNLOAD</ string >
< string name = "type_or_paste_your_url_here" >Type or Paste Your URL Here</ string >
< string name = "start" >START</ string >
< string name = "stop" >STOP</ string >
< string name = "click_on_start_button_to_start_downloading" >Click on Start Button to Start Downloading</ string >
</ resources >
|
Step 5: Designing the box layout
Navigate to app > res > drawable > right-click > new > Drawable Resource File and name that file as box_design_layout and add the below code to that file.
<? xml version = "1.0" encoding = "utf-8" ?>
android:shape = "rectangle" >
< corners
android:bottomLeftRadius = "0dp"
android:bottomRightRadius = "0dp"
android:topLeftRadius = "0dp"
android:topRightRadius = "0dp" />
< stroke
android:width = "1dp"
android:color = "@android:color/black" />
< solid android:color = "@android:color/transparent" />
</ shape >
|
Step 6: Create Util class
Navigate to app > java > package name > right-click > New >Java class and name that file as Utils.java. Add the below code into Utils.java. Below is the code for Utils.java.
import android.content.Context;
import android.os.Environment;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.util.Locale;
public final class Utils {
private Utils() {
}
public static String getRootDirPath(Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File file = ContextCompat.getExternalFilesDirs(context.getApplicationContext(), null )[ 0 ];
return file.getAbsolutePath();
} else {
return context.getApplicationContext().getFilesDir().getAbsolutePath();
}
}
public static String getProgressDisplayLine( long currentBytes, long totalBytes) {
return getBytesToMBString(currentBytes) + "/" + getBytesToMBString(totalBytes);
}
private static String getBytesToMBString( long bytes) {
return String.format(Locale.ENGLISH, "%.2fMb" , bytes / ( 1024.00 * 1024.00 ));
}
} |
Step 7: Working with the MainActivity.java
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.downloader.Error;
import com.downloader.OnCancelListener;
import com.downloader.OnDownloadListener;
import com.downloader.OnPauseListener;
import com.downloader.OnProgressListener;
import com.downloader.OnStartOrResumeListener;
import com.downloader.PRDownloader;
import com.downloader.Progress;
import com.downloader.Status;
public class MainActivity extends AppCompatActivity {
private EditText editTextUrl;
private String path;
private TextView file_downloaded_path, file_name, downloading_percent;
private ProgressBar progressBar;
private Button btnStart, btnCancel, buttonDownload;
private LinearLayout details;
int downloadID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing PRDownloader library
PRDownloader.initialize( this );
// finding edittext by its id
editTextUrl = findViewById(R.id.url_etText);
// finding button by its id
buttonDownload = findViewById(R.id.btn_download);
// finding textview by its id
file_downloaded_path = findViewById(R.id.txt_url);
// finding textview by its id
file_name = findViewById(R.id.file_name);
// finding progressbar by its id
progressBar = findViewById(R.id.progress_horizontal);
// finding textview by its id
downloading_percent = findViewById(R.id.downloading_percentage);
// finding button by its id
btnStart = findViewById(R.id.btn_start);
// finding button by its id
btnCancel = findViewById(R.id.btn_stop);
// finding linear layout by its id
details = findViewById(R.id.details_box);
//storing the path of the file
path = Utils.getRootDirPath( this );
// handling onclick event on button
buttonDownload.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
// getting the text from edittext
// and storing it to url variable
String url = editTextUrl.getText().toString().trim();
// setting the visibility of linear layout to visible
details.setVisibility(View.VISIBLE);
// calling method downloadFile passing url as parameter
downloadFile(url);
}
});
}
@SuppressLint ( "SetTextI18n" )
private void downloadFile( final String url) {
// handing click event on start button
// which starts the downloading of the file
btnStart.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
// checks if the process is already running
if (Status.RUNNING == PRDownloader.getStatus(downloadID)) {
// pauses the download if
// user click on pause button
PRDownloader.pause(downloadID);
return ;
}
// enabling the start button
btnStart.setEnabled( false );
// checks if the status is paused
if (Status.PAUSED == PRDownloader.getStatus(downloadID)) {
// resume the download if download is paused
PRDownloader.resume(downloadID);
return ;
}
// getting the filename
String fileName = URLUtil.guessFileName(url, null , null );
// setting the file name
file_name.setText( "Downloading " + fileName);
// making the download request
downloadID = PRDownloader.download(url, path, fileName)
.build()
.setOnStartOrResumeListener( new OnStartOrResumeListener() {
@SuppressLint ( "SetTextI18n" )
@Override
public void onStartOrResume() {
progressBar.setIndeterminate( false );
// enables the start button
btnStart.setEnabled( true );
// setting the text of start button to pause
btnStart.setText( "Pause" );
// enabling the stop button
btnCancel.setEnabled( true );
Toast.makeText(MainActivity. this , "Downloading started" , Toast.LENGTH_SHORT).show();
}
})
.setOnPauseListener( new OnPauseListener() {
@Override
public void onPause() {
// setting the text of start button to resume
// when the download is in paused state
btnStart.setText( "Resume" );
Toast.makeText(MainActivity. this , "Downloading Paused" , Toast.LENGTH_SHORT).show();
}
})
.setOnCancelListener( new OnCancelListener() {
@Override
public void onCancel() {
// resetting the downloadId when
// the download is cancelled
downloadID = 0 ;
// setting the text of start button to start
btnStart.setText( "Start" );
// disabling the cancel button
btnCancel.setEnabled( false );
// resetting the progress bar
progressBar.setProgress( 0 );
// resetting the download percent
downloading_percent.setText( "" );
progressBar.setIndeterminate( false );
Toast.makeText(MainActivity. this , "Downloading Cancelled" , Toast.LENGTH_SHORT).show();
}
})
.setOnProgressListener( new OnProgressListener() {
@Override
public void onProgress(Progress progress) {
// getting the progress of download
long progressPer = progress.currentBytes * 100 / progress.totalBytes;
// setting the progress to progressbar
progressBar.setProgress(( int ) progressPer);
// setting the download percent
downloading_percent.setText(Utils.getProgressDisplayLine(progress.currentBytes, progress.totalBytes));
progressBar.setIndeterminate( false );
}
})
.start( new OnDownloadListener() {
@Override
public void onDownloadComplete() {
// disabling the start button
btnStart.setEnabled( false );
// disabling the cancel button
btnCancel.setEnabled( false );
// setting the text completed to start button
btnStart.setText( "Completed" );
// will show the path after the file is downloaded
file_downloaded_path.setText( "File stored at : " + path);
Toast.makeText(MainActivity. this , "Downloading Completed" , Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Error error) {
// setting the text start
btnStart.setText( "Start" );
// resetting the download percentage
downloading_percent.setText( "0" );
// resetting the progressbar
progressBar.setProgress( 0 );
// resetting the downloadID
downloadID = 0 ;
// enabling the start button
btnStart.setEnabled( true );
// disabling the cancel button
btnCancel.setEnabled( false );
progressBar.setIndeterminate( false );
Toast.makeText(MainActivity. this , "Error Occurred" , Toast.LENGTH_SHORT).show();
}
});
// handling click event on cancel button
btnCancel.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
btnStart.setText( "Start" );
// cancels the download
PRDownloader.cancel(downloadID);
}
});
}
});
}
} |
NOTE *: If you get any error called “cannot resovle Prdownloader” or “Failed to resolve: com.mindorks.android:prdownloader:0.5.0”
or if the class “Prdownload” in red color unable to use showing errors do these
1. add jcenter() library in build.gradle (project: your app name) like this
repositories {
google()
mavenCentral()
jcenter()
}
2. if cannot find repositories in build.gradle (project: your app name) then you will find it
in settings.gradle(project settings) file last gradle file you have add jcenter() library there
like this
repositories {
google()
mavenCentral()
jcenter()
}
3.then sync the project with gradle files .
4. if you cannot find the “sync now” button in the top of gradle files windows or Tab then you
will find it in File >> sync project with gradle files.
Output: