0

I am using

Intent I=new  Intent(Myactivity.this,MyService.class);

intent to start and stop a service.I have a AsycTask inside this service which wouldn't stop until the task get completed or application is closed. To stop Asynctask on stopping service I have tried calling onDestroyed method as

@Override
public void onDestroy() {
    if (task!=null) {
        if(!task.isCancelled()) {
            task.onCancelled();
            task.cancel(true);
        }
    }
    isRunning=false;
    System.out.println("service destroyed");
    super.onDestroy();
    stopSelf();
}

(which I think is not triggered because the "service destroyed" message is not printed after calling stopService(I) or even when task is finished). Next thing I tried was making Asyctask class static and call cancel(true) method from Myactivity that too didn't help.Any helpful suggestion apreciated.

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
The_ehT
  • 1,202
  • 17
  • 32

1 Answers1

1

Well you need to check within your AsyncTask if it is set to cancel. Check here the AsyncTask documentation, topic "Usage".

// at one point in your doDownload() method check for cancel state
if (isCancelled()) {
    // do a break or just return or what ever you need for a clean exit
}

I am not sure how you exactly try to stop the service but basically that should work.

Community
  • 1
  • 1
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150