0

There is a call to OnDestroy() method in my activity. However, after that, I can still see there is something happening in destroyed activity. E.g. when I add this code to OnCreate:

        Task.Run(async () => {
            while (true) { 
            System.Diagnostics.Debug.WriteLine("PING");
            await Task.Delay(1000);
            }
        });

then I can see PING string in Output console even after OnDestroy was called.

When I launch my activity again, then I can see PING string to be printed twice. After another OnDestroy and activity relaunch, there are 3 PING prints every second.

What is happening here?

Martin Dusek
  • 1,170
  • 3
  • 16
  • 41
  • 2
    That is because you are starting a new asynchronous task which lives independently of the activity lifecycle. Every time you go through onCreate you are creating a new task. – z3n105 Jan 24 '17 at 19:34
  • 1) You start an asynchronous task which (most likely) will be executing even after the `Activity` instance is terminated; 2) when `onDestroy()` returns it [does not mean its instance will be immediately terminated](http://stackoverflow.com/questions/39562914/is-it-possible-for-a-callback-method-to-be-called-after-ondestroy/39563751#39563751). – Onik Jan 24 '17 at 19:49
  • You're creating a memory leak. That's bad. Don't do that. The onDestroy is there for developers to clean up anything holding the activity and your Async task is clearly holding it. – Budius Jan 24 '17 at 22:21

2 Answers2

1

That method above is doing an asynchronous task which would still persist (since it is different thread) even when your activity is destroyed and it will still execute in the future. You can either interrupt/cancel it during onDestroy or whereever you see it fit.

Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
  • 1
    Maybe worth mentioning: the _correct_ way of performing operations in the background is to use Android services. – Krumelur Jan 25 '17 at 07:40
1

All Thread and AsyncronTasks you have started, work until they ends, even if Activity is destroyed.

If you want in Threads something change on UI, then call if(!isDestroeyd()) before

anatoli
  • 1,663
  • 1
  • 17
  • 43