0

I have an app that downloads a file from a server. The download is in the Asynctask. I have a progress bar that shows the download progress. If the file is taking too long to complete downloading I give Cancel request. This just dismisses the progress dialog and when the file is clicked again it does not restart the download. How do I handle this scenario. A lot of research has left me a lot confused...I thought it is as simple as On downloading Show Download progress -> OnCancel, kill the download (unfortunately I cant find a way to kill an Asynctask) -> On click of the file, restart the download.....But alas, I dont seem to get a way...Please help...

Here is the source of what I do...

 class DownloadFileAsync extends AsyncTask<String, String, String> {



            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            //  showDialog(DIALOG_DOWNLOAD_PROGRESS);//to test i commented
                mProgressDialog = new ProgressDialog(Shelf_books.this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                /*mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {
                        // TODO Auto-generated method stub
                        mytask.cancel(true);
                    }
                });*/

                mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        mytask.cancel(true);
                    }
                });
                mProgressDialog.show();
            }

            protected void onProgressUpdate(String... progress) {
                 Log.d("kunal",progress[0]);
                 mProgressDialog.setProgress(Integer.parseInt(progress[0]));
            }

            @Override
            protected void onPostExecute(String unused) {
                dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            }

            @Override
            protected void onCancelled() {
                Log.d("kunal","cancel method");
                running = false;
            }

            @Override
            protected String doInBackground(String... arg1) {
                // TODO Auto-generated method stub
                int count;
                if(isCancelled()==false)//test
                {//test
                try{
                URL url = new URL(arg1[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("kunal", "Lenght of file: " + lenghtOfFile);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];

                long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;
                        publishProgress(""+(int)((total*100)/lenghtOfFile));
                        output.write(data, 0, count);
                    }

                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {
                    Log.d("kunal","exception occured");
                }
                }//test
                return null;
            }

        }
     /*creating async class ends here*/
}

And below is the call for onExecute, this is called on click of a button...

public  void DownloadFile(String fileURL, File directory) {

   /*testing my code here starts */
   try {
   URL u = new URL(fileURL);
    new DownloadFileAsync().execute(fileURL);
  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
Kunal Shah
  • 489
  • 1
  • 4
  • 21

1 Answers1

0

To cancel an AsyncTask, you can call AsyncTask's cancel method. Since you can only call execute one time on an AsyncTask, you'll have to instantiate a new one when the user wants to try the download again.

Eric Levine
  • 13,536
  • 5
  • 49
  • 49
  • How do I fork one more instance? – Kunal Shah Sep 05 '12 at 13:51
  • I have given the .onExecute method...but it does not seem to work – Kunal Shah Sep 05 '12 at 14:07
  • It would help if you edit your answer and add it some samples of your code. Let's say your AsyncTask class is called MyAsyncTask. To "fork one more instance" you would do: new MyAsyncTask.execute(); – Eric Levine Sep 05 '12 at 14:17
  • the problem is that it doesnt dwnload – Kunal Shah Sep 06 '12 at 13:50
  • @KunalShah Are you getting any kind of errors or exceptions? Did you add the Internet permission to your manifest (see: http://stackoverflow.com/questions/2378607/what-permission-do-i-need-to-access-internet-from-an-android-application) ? – Eric Levine Sep 06 '12 at 17:22
  • @KunalShah Try stepping through your code with the debugger to see exactly what is going wrong. Its really hard for someone to help you without details of the problem. – Eric Levine Sep 07 '12 at 14:12