Filedownloader: Get file size prior to start downloading it

Created on 31 Jul 2016  ·  19Comments  ·  Source: lingochamp/FileDownloader

I've started using the library and gone through the simple implementation, although it doesn't tell about implementation of getting size of file before actually downloading it.

What i tried so far is

String downloadLink = VALID_FILE_URL;
String filePath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "file.mp4";
Logger.log(String.valueOf(FileDownloader.getImpl().create(downloadLink).setPath(filePath).getSmallFileTotalBytes()));

but it's returning 0.00 every time i execute the above code.

question

All 19 comments

can't use FileDownloader.getImpl().create(downloadLink).setPath(filePath).getSmallFileTotalBytes() to get so far bytes of a running task.

You can get so far bytes of a running task by fellow ways:

  1. in methods of FileDownloadListener which attached to the task object.
  2. use FileDownloader#getSoFar through the task Id.

So it's not possible to get the size of file before starting a download, correct?

No, you can use FileDownloader#getSoFar.

My motive is to get the TotalBytes of the file to show the size of the file, but FileDownloader#getSoFar will return me how many Bytes of data have been downloaded so far.

If you start a task, until it completed downloading, FileDownloader will store its downloading data in the filedownloader database, which used for resuming from the breakpoint. And you also can get downloaded so far bytes from the filedownloader database through FileDownloader#getSoFar.

2333...

If you need get the TotalBytes, Just use FileDownloader#getTotal.

Another way: because before start fetching the data from the network, FileDownloader will pre-allocate total length for the file to store the data, so you also can get the total bytes through new File(FileDownloadUtil.getTempPath(filePath)).length() if the task not completed downloading yet, it would always be the TotalBytes.

FileDownloader#getTotal the implementation of this states that it's been deprecated and point to FileDownloader#getSmallFileTotalBytes() which i already did in my example.

NOT BaseDownloadTask#getTotalBytes.

I saidFileDownloader#getTotal, it isn't been deprecated.

Can you please provide a sample code snippet to do it, I'm still not able to understand the APIs behind.

I don't know what's your problem.


If you have any problem, I really recommend simply clone the demo project, and check TasksManagerDemoActivity.


For example:

Start Task(s): https://github.com/lingochamp/FileDownloader/wiki/Start-downloading .

In downloading: You can get TotalBytes/SofarBytes in methods of FileDownloadListener.

In other status : You also can just easily get TotalBytes/SofarBytes through FileDownloader.getImpl().getTotal(downloadId)/FileDownloader.getImpl().getSoFar(downloadId). It isn't need the task is running.


What is downloadId? @see FileDownloadUtils#generateId, If you create a task and start it, the return value of BaseDownloadTask#start() is downloadId.

this is now I've implemented

int downloadId = FileDownloader.getImpl().create(downloadLink).setPath(filePath).getId();
Log.i("", String.valueOf(FileDownloader.getImpl().getTotal(downloadId)));

still returning 0

..... If you just need the downloadId, you can use FileDownloadUtils#generateId or store the return value after you start the task. DO NOT create a task object, just for its downloadId, this is a very NOT-RECOMMEND and bad way.


For the 0, Please check your Logcat window in IDE, Is there a warning log in the IDE Logcat window: xxx, but the download service isn't connected yet. . You need to start FileDownloadService before invoke getTotal.


RECOMMEND: clone the demo project, And check the TasksManagerDemoActivity. Your case is very very basic and simple, and I think after you ran the demo project, you will know everything.

DEMO CODE to getTotalBytes(There are three ways):

// WAY 1:
long totalBytes;
final int downloadId = FileDownloader.getImpl().create(url)
        .setListener(new FileDownloadListener() {
            // in the bellow callback methods, you can get totalBytes.
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void completed(BaseDownloadTask task) {

            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {

            }

            @Override
            protected void warn(BaseDownloadTask task) {

            }
        }).start();

// WAY 2:
File downloadedFile = new File(path);
if (downloadedFile.exists()) {
    totalBytes = downloadedFile.length();
} else {
    File downloadingTempFile = new File(FileDownloadUtils.getTempPath(path));
    if (downloadingTempFile.exists()) {
        totalBytes = downloadingTempFile.length();
    } else {
        totalBytes = 0;
    }
}

// WAY 3:
// 1. make sure FileDownloadService is connected.
if (FileDownloader.getImpl().isServiceConnected()) {
    // 2. get Total from the filedownloader database in FileDownloadService.
    totalBytes = FileDownloader.getImpl().getTotal(downloadId);
} else {
    final FileDownloadConnectListener listener = new FileDownloadConnectListener() {
        @Override
        public void connected() {
           // 2. get Total from the filedownloader database in FileDownloadService.
            totalBytes = FileDownloader.getImpl().getTotal(downloadId);
        }

        @Override
        public void disconnected() {

        }
    };

    FileDownloader.getImpl().addServiceConnectListener(listener);
    // waiting to connect.


    // DO NOT FORGET to remove ServiceConnectListener when you no need it.
}

You also can generate the downloadId by URL and PATH. downloadId = FileDownloadUtils.generateId(url, path);.

I'm really thankful for your time and your amazing work

I actually thinks you did not understand my use case, but I finally managed to did this way

FileDownloader.getImpl().create(downloadLink).setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        String dTotal = String.format(Locale.getDefault(), "%.2f", (float) totalBytes / 1048576);
                        Logger.log(dTotal);
                        task.pause();
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {

                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {

                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                }).start();

OK. I think I know, now. If you want to get TotalBytes through FileDownloader instead of standalone API.

Though I don't recommend, but you can get totalBytes in FileDownloadListener#connected, it is better than in FileDownloadListener#progress which you did.

I think we're heading to the correct direction, but now the problem is I can't override the FileDownloadListener#connected method

Method signature indicates that it can't be overridden I think, please help

/**
     * Already connected to the server, and received the Http-response.
     *
     * @param task       The task
     * @param etag       ETag
     * @param isContinue Is resume from breakpoint
     * @param soFarBytes Number of bytes download so far
     * @param totalBytes Total size of the download in bytes
     * @see IFileDownloadMessenger#notifyConnected(MessageSnapshot)
     */
    protected void connected(final BaseDownloadTask task, final String etag,
                             final boolean isContinue, final int soFarBytes, final int totalBytes) {

    }

No, you can, please feel free to do it:

FileDownloader.getImpl().create(url)
      .setListener(new FileDownloadListener() {
          @Override
          protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
          }

          @Override
          protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
              super.connected(task, etag, isContinue, soFarBytes, totalBytes);
              // here.
          }

          @Override
          protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

          }

          @Override
          protected void completed(BaseDownloadTask task) {

          }

          @Override
          protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

          }

          @Override
          protected void error(BaseDownloadTask task, Throwable e) {

          }

          @Override
          protected void warn(BaseDownloadTask task) {

          }
      })
Was this page helpful?
0 / 5 - 0 ratings