package com.mcmu.juanjesus.mcmuasteroids.tasks;

import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Toast;

import com.mcmu.juanjesus.mcmuasteroids.activities.MainActivity;

public class FactorialTask extends AsyncTask<Integer, Integer, Integer>{

    // region Private Member Variables

    private Activity callingActivity;
    private ProgressDialog progressDialog;

    // endregion


    public FactorialTask(Activity callingActivity) {
        this.callingActivity = callingActivity;
        progressDialog = new ProgressDialog(this.callingActivity);
    }

    @Override
    protected void onPreExecute() {

        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();

    }

    @Override
    protected Integer doInBackground(Integer... n) {

        int res = 1;
        for (int i = 1; i <= n[0]; i++) {
            res *= i;
            SystemClock.sleep(1000);
            publishProgress(i*100 / n[0]);
        }
        return res;
    }

    @Override
    protected void onProgressUpdate(Integer... precentage) {

        progressDialog.setProgress(precentage[0]);
    }

    @Override
    protected void onPostExecute(Integer result) {

        progressDialog.dismiss();
        Toast.makeText(callingActivity, "Factorial: " + result, Toast.LENGTH_SHORT).show();
    }
}

@@ -138,16 +138,56 @@
 Dialog;%0A
+import android.content.DialogInterface;%0A
 import a
@@ -207,16 +207,16 @@
 ncTask;%0A
-
 import a
@@ -939,12 +939,11 @@
 ble(
-fals
+tru
 e);%0A
@@ -1049,16 +1049,256 @@
 how();%0A%0A
+        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() %7B%0A            @Override%0A            public void onCancel(DialogInterface dialog) %7B%0A                FactorialTask.this.cancel(true);%0A            %7D%0A        %7D);%0A
     %7D%0A%0A 
@@ -1418,16 +1418,34 @@
  %3C= n%5B0%5D
+ && !isCancelled()
 ; i++) %7B
@@ -1814,24 +1814,24 @@
 .dismiss();%0A
-
         Toas
@@ -1915,11 +1915,76 @@
 );%0A    %7D
+%0A%0A    @Override%0A    protected void onCancelled() %7B%0A        %0A    %7D
 %0A%7D%0A

Make factorial async task cancellable.