📌  相关文章
📜  如何在 Android 应用程序中使用 PRDownloader 库?

📅  最后修改于: 2022-05-13 01:55:07.235000             🧑  作者: Mango

如何在 Android 应用程序中使用 PRDownloader 库?

PRDownloader 库是一个适用于 android 的文件下载器库。它带有暂停并在下载文件时恢复支持。该库能够从互联网下载大文件,可以下载任何类型的文件,如图像、视频、pdf、apk 等。它提供了许多功能,可以帮助用户轻松高效地从互联网下载文件。使用此库,您还可以使用下载 id 检查下载状态,并可以使用下载 id 执行许多其他重要操作。这个库包含许多重要的方法,可以让用户完全控制处理文件的下载状态,如暂停、取消、恢复等。您可以使用这个库发出以下请求:

暂停下载请求:

PRDownloader.pause(downloadId);

取消下载请求:

// 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();

恢复下载请求:

PRDownloader.resume(downloadId);

获取下载请求的状态:



Status status = PRDownloader.getStatus(downloadId);

我们将在本文中构建什么?

下面给出了一个示例视频,以了解我们将在本文中做什么。请注意,我们将使用Java语言来实现这个项目。

分步实施

第 1 步:创建一个新项目

要在 Android Studio 中创建新项目,请参阅如何在 Android Studio中创建/启动新项目。然后在名称字段中输入您的应用程序名称并从语言下拉菜单中选择Java 。

第二步:添加依赖

要添加依赖项,请导航到app > Gradle Scripts > gradle.build(Module: app)并在依赖项部分添加以下依赖项。添加依赖项后同步您的项目。

implementation 'com.mindorks.android:prdownloader:0.6.0'

第 3 步:添加 Internet 权限

导航到app > manifest > AndroidManifest.xml并添加互联网权限。

步骤 4:使用 activity_main.xml 文件



导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码

XML


  
    
    
  
    
    


XML

    GFG PRDownloader Library
    DOWNLOAD
    Type or Paste Your URL Here
    START
    STOP
    Click on Start Button to Start Downloading


XML


  
    
  
    
  
    
      


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));
    }
}


Java
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);
                                // restting the download precent
                                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);
                    }
                });
            }
        });
    }
}


下面是 Strings.xml 文件的代码

XML


    GFG PRDownloader Library
    DOWNLOAD
    Type or Paste Your URL Here
    START
    STOP
    Click on Start Button to Start Downloading

第 5 步:设计盒子布局

导航到app > res > drawable > 右键单击 > new > Drawable Resource File并将该文件命名为box_design_layout并将以下代码添加到该文件中。

XML



  
    
  
    
  
    
      

第 6 步:创建 Util 类

导航到app > Java > 包名称 > 右键单击 > 新建 > Java类并将该文件命名为Utils.java 。Java。将以下代码添加到Utils.js 中。Java。下面是Utils的代码。Java。

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));
    }
}

第 7 步:使用 MainActivity。Java

转到主活动。 Java文件,参考如下代码。下面是MainActivity的代码。 Java文件。代码中添加了注释以更详细地理解代码。

Java

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);
                                // restting the download precent
                                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);
                    }
                });
            }
        });
    }
}

输出: