I tried using Android's open source file download manager Fetch

About this article

This time, I will implement it in the app I am developing! I was wondering if I should use the DownloadManager, and when I was looking into it, I thought it would be good to find it, so I would like to use it! When I looked it up, there wasn't much information in Japanese, so I'd like to share the information, so I'll write it! I will use it for the first time, so please let me know if you make a mistake! Click here for the GitHub page

This environment

In this case, the file is stored in Firebase CLoudStrage and we'll get the Download URL and use that URL to download. The usage of Firebase Cloud Strage is omitted.

Preparation

First, add a dependency to build.gradle in the application folder. This time, I will use it on Android X, so

implementation "androidx.tonyodev.fetch2:xfetch2:3.1.4"

To add. Once added, sync.

Creating an Activity

This time, I created it as DownloadActivity. The layout is a simple layout with just a button and a progress bar. image.png

Get CloudStrage Download URL

Get the URL for Download. In the case of Cloud Strage this time, since it is set only for people who have been authenticated by the security rule, check the login status with Firebase Auth. This time, run it in onCreate and set the button to be enabled only when you are logged in. Also, if the user isn't null, try to get a Strage reference. If you use it in an actual environment, please be a little more careful. Also set onClickListener.


Button downloadButton = findViewById(R.id.downloadbutton);
ProgressBar progressBar = findViewById(R.id.progressBar);

downloadButton.setOnClickListener(onClickListener);
if(FirebaseAuth.getInstance().getCurrentUser() == null) {
   downloadButton.setEnabled(false);
   }else {
    firebaseStorage = FirebaseStorage.getInstance();
    storageReference = firebaseStorage.getReference().child("Path on Firebase Strage");
   }

View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    };

I will write the process in onClick. First of all, when the button is pressed, get the URL for download.

storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                }
            });

If the acquisition is successful, uri will return the download URL.

Download process

Create an instance of Fetch. This time, it was generated by onCreate, but please adjust it according to the situation. Set the number of simultaneous downloads in setDownloadCurrentLimit.

 FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(this)
                    .setDownloadConcurrentLimit(2)
                    .build();
            fetch = Fetch.Impl.getInstance(fetchConfiguration);

Then generate a download request. This is handled within the onClick listener. uri is the download url I got earlier For filePath, specify the save destination of the terminal as a String.

downloadRequest = new Request(uri.toString(),filePath );

Generate a listener. When using it in production, let's write the process a little more properly.


FetchListener fetchListener = new FetchListener() {
        @Override
        public void onWaitingNetwork(@NotNull Download download) {
        downloadStatusTextView.setText("Waiting for network connection");
        }

        @Override
        public void onStarted(@NotNull Download download, @NotNull List<? extends DownloadBlock> list, int i) {
        downloadStatusTextView.setText("Downloading");
        }

        @Override
        public void onError(@NotNull Download download, @NotNull Error error, @Nullable Throwable throwable) {
        downloadStatusTextView.setText("Download error");
        }

        @Override
        public void onDownloadBlockUpdated(@NotNull Download download, @NotNull DownloadBlock downloadBlock, int i) {
        }

        @Override
        public void onAdded(@NotNull Download download) {
        }

        @Override
        public void onQueued(@NotNull Download download, boolean waitingOnNetwork) {
        }

        @Override
        public void onCompleted(@NotNull Download download) {
        downloadStatusTextView.setText("Download complete");
        }

        @Override
        public void onProgress(@NotNull Download download, long etaInMilliSeconds, long downloadedBytesPerSecond) {
            int progress = download.getProgress();
            progressBar.setProgress(progress);
        }

        @Override
        public void onPaused(@NotNull Download download) {
        }

        @Override
        public void onResumed(@NotNull Download download) {
        }

        @Override
        public void onCancelled(@NotNull Download download) {
        }

        @Override
        public void onRemoved(@NotNull Download download) {
        }

        @Override
        public void onDeleted(@NotNull Download download) {
        }
    };

Set the listener.


        fetch.addListener(fetchListener);

The download will start.

        fetch.enqueue(downloadRequest, updatedRequest -> {
        }, error -> {
        });

When the download is complete, the listener onCompleted is called. If you have multiple downloads

download.getId()

You can get the download ID with.

You can easily interrupt the download.

//pause
fetch.pause(downloadrequest.getId());
//Cancel
fetch.cancel(downloadrequest.getId());

You can also download it only when using Wifi.

//All types
downloadRequest.setNetworkType(NetworkType.ALL);
//Wifi only
downloadRequest.setNetworkType(NetworkType.WIFI_ONLY);

Besides, it seems that you can manage downloads collectively as a group.

Summary

It's a bit messy, but it's very useful! However, if the file already exists in the download destination, it will not be downloaded, but it seems to be onComplete. I responded by renaming the download file, but what should I do? There doesn't seem to be an overwrite option. If anyone knows, please let me know! Well then

Recommended Posts

I tried using Android's open source file download manager Fetch
I tried using Gson
I tried using TestNG
I tried using Galasa
I tried using azure cloud-init
I tried using Apache Wicket
I tried using Java REPL
I tried source code analysis
I tried using anakia + Jing now
I tried using JOOQ with Gradle
I tried using Java8 Stream API
I tried using WebAssembly Stadio (2018/4/17 version)
I tried using Java memo LocalDate
I tried using GoogleHttpClient of Java
I tried using Elasticsearch API in Java
I tried using Realm with Swift UI
I tried using Java's diagnostic tool Arthas
I tried using UICollectionViewListCell added from Xcode12.
I tried using Scalar DL with Docker
I tried using OnlineConverter with SpringBoot + JODConverter
It's new, but I tried using Groonga
I tried using OpenCV with Java + Tomcat
Save files and folders using File Manager
I tried to build Ruby 3.0.0 from source
I tried using ECR Public instead of Docker Hub (Docker Hub Download Rate Limit measures)