Android stop AsyncTask

AsyncTask is an easy class to perform a long-run task in background. For example, when you download a file or fetch data from a remote server, AsyncTask is useful. AsyncTask is easy to integrate with ProgressDialog to show the task progress to the user. A common problem that happens when you use AsyncTask with ProgressDialog is that once the user presses the back button to cancel the task, the progress dialog is closed but the AsyncTask still continues its work. In this Android tip, I am going to share my solution of this problem to you.
To stop AsyncTask when the user cancels the task by pressing the back button or by other ways, you need to implement the OnCancelListener interface to the ProgressDialog. In the onCancel(), you can call the cancel() method of AsyncTask to stop the background process. You should note that to implement the OnCancelListener to work successfully, you need to make sure that the dialog is cancelable by passing true to the setCancelable() method of the dialog instance.

Below is the complete code written in MainActivity class to demonstrate the solution mentioned above. The example code is about using AsyncTask to download a file from the internet. The download progress is displayed in the ProgressDialog. The user can stop the download task while it is progressing. The incomplete download file is automatically deleted.




package com.example.stopasynctask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

AsyncTask<String, Integer, Void> ATask;
Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
ATask=new BackTask();
ATask.execute("http://www.worldbestlearningcenter.com/index_files/pdf-files/SystemAnaDes-chapterV.pdf");
}


//background process to download the file from server
  private class BackTask extends AsyncTask<String,Integer,Void>{
  ProgressDialog pd=null;
  String outputPath="";
  protected void onPreExecute(){
     super.onPreExecute();
     //Lock rotation while downloading       
   int currentOrientation = getResources().getConfiguration().orientation;
   if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
   }
   else {
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
   }
  
   // ProgressDialog settings
     pd = new ProgressDialog(context);
     pd.setTitle("Downloading the file...");
     pd.setMessage("Please wait.");
     pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     pd.setMax(100);
   pd.setIndeterminate(false);     
     pd.setCancelable(true); // Make sure the AsyncTask cancelable
     pd.setOnCancelListener(new OnCancelListener(){ // This code works when the dialog is canceled.
public void onCancel(DialogInterface dialog) {
try{
File f=new File(outputPath);
f.delete(); // Delete the incomplete download file

if(ATask!=null) ATask.cancel(true); // Stop AsyncTask   

}catch(NullPointerException npe){
  
}
}
});
     // Show the dialog
     pd.show();
    
     }  
  
     protected Void doInBackground(String...params){
     URL url;
     int count;
     HttpURLConnection con=null;
     InputStream is=null;
     FileOutputStream fos=null;
     try {
    
     url = new URL(params[0]);
     try {
    
    
     con=(HttpURLConnection)url.openConnection();
     is=con.getInputStream();
     String urlPath=url.getPath();
     String filename=urlPath.substring(urlPath.lastIndexOf('/')+1);
     outputPath=Environment.getExternalStorageDirectory()+"/"+filename;
     fos=new FileOutputStream(outputPath);
     int lenghtOfFile = con.getContentLength();
     byte data[] = new byte[1024];   
     long total = 0;   
     while ((count = is.read(data)) != -1) {
     total += count;
     // publishing the progress
     publishProgress((int)((total*100)/lenghtOfFile));         
     // writing data to output file
     fos.write(data, 0, count);
     }
     // Ensure buffer data is written out
     fos.flush();
    
    
       } catch (IOException e) {
       e.printStackTrace();
       } finally{
       try {
       if(is!=null)      
       is.close();
       if(fos!=null)
       fos.close();
       // set orientation to default
       setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    
       }


     } catch(MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     }
    
     return null;
    
     }  
    
     protected void onProgressUpdate(Integer... progress) {
       if(pd!=null)
       pd.setProgress(progress[0]);
     }
    
     protected void onPostExecute(Void result){
     if(pd!=null)
     pd.dismiss();  // close the dialog
     // set orientation to default
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
      
    
     }    
  
    
    }


}


Android-stop-AsyncTask

Posted by: Dara | post date: 11-27-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.