title: How to detect application exit on android?
body: <p>How to execute some code on application exit? I want to delete temp data on application exit. By application exit i mean that app is not running minimized in background and its totally gone.</p>
  <p>I tried to make service that runs in separate process, the service is checking if app process is not running it should delete temp folder. With this approach temp folder is not always deleted because process is still running with the lowest priority.</p>
  <p>I can't do this in OnDestroy().</p>
  <p>Service code:</p>
  <pre><code>[Service(Process = &quot;com.lobomonitor&quot;)]
  [IntentFilter(new string[] { &quot;com.androidgui.ProcessMonitorService&quot; })]
  public class ProcessMonitorService : Service
  {
      public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
      {
          Thread processThread = new Thread(() =&gt;
              {
                  ActivityManager actManager = (ActivityManager) this.GetSystemService(ActivityService);
                  while (true)
                  {
                      Thread.Sleep(1000);
                      IList&lt;ActivityManager.RunningAppProcessInfo&gt; procList = actManager.RunningAppProcesses;
                      procList.Any(i =&gt; i.ProcessName.Equals(&quot;com.androidgui&quot;));
                      if (!procList.Any(i =&gt; i.ProcessName.Equals(&quot;com.androidgui&quot;)))
                      {
                              FolderManager.Singleton.DeleteTempFolder();
                              break;
                      }
                  }
              });
          processThread.Start();
          return StartCommandResult.RedeliverIntent;
      }
  
      public override IBinder OnBind(Intent intent)
      {
          return null;
      }
  }
  </code></pre>