title: Cancelling Android notifications when the service is automatically killed by the system
body: <p>I have an application that implements <code>MediaBrowserServiceCompat</code>. When playing music, it runs in the foreground, with a media control notification that the system makes non-dismissible. When paused, it comes out of the foreground, and the notification is retained. Standard stuff.</p>
  
  <p>When this service is automatically killed by the system, the notification is not removed.</p>
  
  <p>You can simulate this by putting the app in the non-foreground paused state, leaving the app, and issuing this command:</p>
  
  <pre><code>adb shell am kill com.myapp.package
  </code></pre>
  
  <p>The notification remains. You get this Logcat message:</p>
  
  <pre><code>W/ActivityManager: Scheduling restart of crashed service com.myapp.package/com.myapp.package.playback.platform.AndroidMediaService
  </code></pre>
  
  <p>None of the obvious hooks (e.g. <code>onDestroy</code>, <code>onTaskRemoved</code> etc) on the service appear to be called - it seems to be outright killed. Because the service is started with <code>START_NOT_STICKY</code>, we also don't get <code>onCreate</code> called on a new instance either.</p>
  
  <p>A partial solution to this is to make the service sticky, and cancel the notifications when the service <em>is</em> revived. However this can take significant time to actually happen, during which the notification doesn't work, so isn't ideal. It may also have further consequences.</p>
  
  <p>Other applications seem to have no trouble with this.</p>
  
  <p>Repeat this scenario (pause, leave app) and carry out the commands, for example on Google Play Music:</p>
  
  <pre><code>adb shell am kill com.google.android.music
  </code></pre>
  
  <p>or Spotify:</p>
  
  <pre><code>adb shell am kill com.spotify.music
  </code></pre>
  
  <p>and you find that their notifications disappear immediately as if they are cancelled on teardown.</p>
  
  <p>What might they be doing to make this happen?</p>