Martin Dusek
Martin Dusek

Reputation: 1292

Android activity lives after OnDestroy

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?

Upvotes: 0

Views: 578

Answers (2)

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

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.

Upvotes: 1

marina
marina

Reputation: 1680

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

Upvotes: 1

Related Questions