user9555243
user9555243

Reputation: 155

How do I stop my AsyncTask from downloading further?

I am using AsyncTask to download a file. It also shows a progress dialog and has a cancel button, when I click cancel it is supposed to stop the AsyncTask from downloading further but it is not doing anything.

cancel button code:

 new DownloadFileAsync().cancel(true);

Asynctask:

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {
        if (!isCancelled()) {
            File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File FileDirectory = new File(dir, guessed_file_name);
            int count;
            try {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();
                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(FileDirectory);
                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) {
            }
        }
        return null;
    }

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

    @Override
    protected void onPostExecute(String unused) {
        Toast.makeText(getBaseContext(), "download completed!", Toast.LENGTH_LONG).show();
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        finish();
    }
}

}

Upvotes: 0

Views: 100

Answers (4)

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5636

For this, you need to create an object and then use that object for execution as well as canceling the task.

So for starting AsyncTask as per your code, you must be doing

new DownloadFileAsync().execute(<your inputs>);

What you need to do it, declare a class level global variable and use that for start execution

DownloadFileAsync mDownloadFileAsync = null; //declare as class global 

mDownloadFileAsync = new DownloadFileAsync();

mDownloadFileAsync.execute(<your inputs>);

For canceling use this DownloadFileAsync instance

if (mDownloadFileAsync != null && mDownloadFileAsync.getStatus == AsyncTask.Status.Running){

    mDownloadFileAsync.cancel(true);

}

And also modify your while loop condition inside AsyncTask as mentioned by @Gabe Sechan and @Miraz Mahmud

while ((count = input.read(data)) != -1 && !isCancelled())

Upvotes: 0

Miraz Mahmud
Miraz Mahmud

Reputation: 11

It's seems you check isCancelled() only once before the download started. add the checking on progress like below

while (((count = input.read(data)) != -1) && !isCancelled()) {

}

Upvotes: 0

Faisal
Faisal

Reputation: 725

You can't do it like this. You need reference to your asynctask. 1. first you need to create object

DownloadFileAsync downloadTask = new DownloadFileAsync();

2. execute it

dowloadTask.execute();

3. on this object reference u can call .cancel(true)

downloadTask.cancel(true);

Upvotes: 1

Gabe Sechan
Gabe Sechan

Reputation: 93569

You're only checking isCanceled once. You need to do it every so often within the function as well, or it won't actually stop. A good place is in your while loop, change it into while ((count = input.read(data)) != -1 && !isCancelled())

Upvotes: 0

Related Questions