Apache commons net ftp unable to stop download when hitting back button

25 views Asked by At

Hey all I am trying to figure out how to do a nice, clean stop of a downloading file if I hit the back button during the download process.

I have the back button detection like this:

mProgress = new ProgressDialog(activity){
   @Override
   public void onBackPressed() {
        mProgress.cancel();
        mProgress.dismiss();

        if (ftp.isConnected()) {
          try {
                 abortDownload = true;
          } catch (Exception e) {
                 Log.d("", "error: " + e.getMessage());
          }
        }
   }

   mProgress.setMessage("Downloading new apk .. Please wait...");
   mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   mProgress.show();
};

And once the abortDownload is set to true it triggers this part of the code which is already looping in order to get the current % downloaded:

CountingOutputStream cos = new CountingOutputStream(output) {
    protected void beforeWrite(int n) {
         super.beforeWrite(n);

         if (abortDownload) {
            try {
                output.close();
                abortDownload = false;
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
         } else {
             int percent = (int) Math.round((getCount() * 100.0) / lenghtOfFile);
             mProgress.setProgress(percent);
         }
    }
};

The output.close(); does seem to stop the download but it never continues after the ftp.logout(); part.

If I do ftp.disconnect(); and remove the ftp.logout(); it goes into one of its catches:

} catch (IOException e) {
   Log.d("FTP_DOWNLOAD", "ERROR IOException:" + e);
}

Which the error is

org.apache.commons.net.io.CopyStreamException: IOException caught while copying.

So I am not sure how to do this since I'm not seeing a lot of examples around dealing with hitting the back button while its downloading.

0

There are 0 answers