title: Android: Run code when application is permanently closed
body: <p>So I have code that I want called when my application is closed. Not just when it is sent to the background or the surface is destroyed. How do I do this? Is there a method that I can override in a <code>SurfaceView</code> or <code>Activity</code> class?</p>
  
  <p><strong>New Edit</strong> - current <code>BackgroundService</code> class:</p>
  
  <pre><code>public class BackgroundService extends Service {
      private String savedString;
  
      public void onCreate() {
          System.out.println("Service created");
          super.onCreate();
      }
  
      public int onStartCommand(Intent intent, int flags, int startId) {
          System.out.println("start command: ");
          savedString = intent.getStringExtra("myString);
          return super.onStartCommand(intent, flags, startId);
      }
  
      public IBinder onBind(Intent intent) {
          return null;
      }
  
      public void onTaskRemoved(Intent rootIntent) {
          System.out.println("the saved string was: " + savedString);
          super.onTaskRemoved(rootIntent);
      }
  
      public void onDestroy() {
           System.out.println("destroyed service");
           super.onDestroy();
      }
  }
  </code></pre>
  
  <p>Where I then have this in my other class:</p>
  
  <pre><code> Intent serviceIntent = new Intent(activity.getApplicationContext(), BackgroundService.class);
   serviceIntent.putExtra("myString", "this is my saved string");
   activity.startService(serviceIntent);
  </code></pre>