0

I'm trying to display a Dialog when any exception occurs in doInBackground method of AsyncTask. I know I can't display a dialog while previous task is running. So for this I tried to Cancel (finish) AsyncTask like this,

try {
    response= HttpService.doServerRequest(params);          
} catch(Exception e){
    task.cancel(true);    //Cancelling AsyncTask
    CustomException.onException(CurrentActivityName.this);          
} 

I have created a CustomException class for handling all exceptions and for displaying a dialog that will tell some error has occurred. I know this type of question is already asked here but I am not getting any solution that's why I am asking.

Is there any way to finish all previous activity or finish AsyncTask ?

Please help.

Thanks in Advance.

EdmDroid
  • 1,350
  • 1
  • 11
  • 25
Android
  • 183
  • 1
  • 13
  • Finishing the `AsyncTask` from inside the `AsyncTask` or from somewhere else? – FD_ Apr 01 '14 at 09:20
  • Look [here](http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2034238#2034238) or [here](http://stackoverflow.com/search?q=how+to+exit+an+android+app) – WHDeveloper Apr 01 '14 at 09:22
  • @FD_ : Inside `AsyncTask` – Android Apr 01 '14 at 09:23

2 Answers2

0

Stopping an AsyncTask from inside is quite easy:

HTTPResponse response = null;
try {
    response = HttpService.doServerRequest(params);          
} catch(Exception e){         
} 

if (response == null) return null;

You simply have to return null, or any other object that you can use to tell in onPostExecute() whether the task was successful or not.

FD_
  • 12,947
  • 4
  • 35
  • 62
0

1.finish all previous activity you just call finish method !or set the activity as a singleton mode (actually, I do not clear what your mean)

2.if your want finish AsyncTask . you should note that AsyncTask in different Android version has different features

below 4.0.x AsyncTask task.cancel method cant stop the AsyncTask running , It just set a flag as ture ,and nothing , your should get the flag value ,and decide what to do, for example :

 task.cancel(true);

   if(task.iscancel()){
       CustomException.onException(CurrentActivityName.this)
      // or other stuff ,what you want !
    }

above 4.0.x It will work exactly ! if you call task.cancel(true); the task will stop running

Fooyou
  • 91
  • 1