Issue
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();
}
}
}
Solution
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())
Answered By - Rajen Raiyarela
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.