public override void OnDestroy() { Console.Error.WriteLine("--------------------------- Destroying Service ---------------------------"); base.OnDestroy(); AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper; // the service helper will be null if we failed to create it within OnCreate, so first check that. also, // OnDestroy can be called either when the user stops Sensus (in Android) and when the system reclaims // the service under memory pressure. in the former case, we'll already have done the notification and // stopping of protocols; however, we have no way to know how we reached OnDestroy, so to cover the latter // case we're going to do the notification and stopping again. this will be duplicative in the case where // the user has stopped sensus. in sum, anything we do below must be safe to run repeatedly. if (serviceHelper != null) { serviceHelper.Logger.Log("Destroying service.", LoggingLevel.Normal, GetType()); NotifyBindingsOfStop(); serviceHelper.StopProtocols(); serviceHelper.SetService(null); } }