How can I detect when my app gets tombstoned so that I can kill it

How to Immediately Detect Tombstoning for Background Location Tracking App So I Can Kill the App

I have created a Windows Phone 8 app that uses background location tracking.  In the emulator, when I simulate tombstoning by opening a bunch of apps until my app is no longer in the backstack, my app is actually still running in the background and talking to the Azure server.

If my app is not visible as an "open" app to the user, I don't want it running in the background at all.  How can I detect when my app gets tombstoned so that I can kill it?
Since tombstoning removes the app from user visibility (including backstack), it seems that the OS would automatically disallow continued background tracking, but it allows it.
Are you completely sure that your app was tombstoned while background tracking continued? You can only know by checking after your app has reactivated. One way to check is the IsApplicationInstancePreserved flag in the Activated event:

        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            if (e.IsApplicationInstancePreserved)
            {
                // activated from dormant state (probably includes background tracking)
            }
            else
            {
                // activated from tombstoned state
            }
        }

It isn't clear from the documentation how background tracking fits into the application lifecycle. It doesn't fit the model of a "normal" app, where if it isn't in the foregound, then it is dormant and not running. The concept of tombstoning an app that is still running doesn't make sense to me. I suspect that background tracking is never tombstoned, and simply terminated if the system needs to reclaim resources.

BTW, the app stack that appears when holding the Back key provides no indication of tombstone state. It simply displays the most recent 8 apps that are currently active (i.e. not closed, includes both dormant and tombstoned). Apps pushed off the LRU display list are still accessible if you keep pressing the back key, and those can also be either dormant or tombstoned as well.

Copyright © 2007-2012 www.chuibin.com Chuibin Copyright