Stopping a foreground service on Android when the application crashes
<p>I have an Android application where I implement a Service which interacts with some hardware over a Bluetooth serial connection. The setup of this connection is slow, so I decided to keep the service in the foreground, so if/when you want to view another application, the connection is ready to go (pseudocode follows):</p>

<pre><code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    start();
    return (START_STICKY);
}

@Override
public void onDestroy() {
    stop();
}
</code></pre>

<p><code>start()</code> and <code>stop()</code> are private methods which start communication with the hardware, and in start's case, creates a <code>Notification</code> for use in <code>startForeground()</code> My <code>Activity</code> will call</p>

<pre><code> @Override
 public void onStart() {
     super.onStart();
     // Start the service

     Intent intent = new Intent(getApplicationContext(), MyService.class);
     ComponentName theService = startService(intent);
     //this is to register the functions I need to handle functions my Activity calls
     // to the service
     bindService(intent, svcConn, BIND_AUTO_CREATE);
 }

 @Override
 public void onStop() {
     super.onStop();

     if (theService != null) {
         unbindService(svcConn);
         theService = null;
         if (isFinishing()) {
             stopService(new Intent(getApplicationContext(), MyService.class));
         }
     }
 }
</code></pre>

<p>I've had to add a "Quit" menu item to make sure that the <code>Service</code> shuts down. Worse, if my app crashes, I have to go in and manually kill the <code>Service</code>. Is there a way to elegantly kill the <code>Service</code> if things go horribly wrong, or am I abusing the purpose of a <code>Service</code>, and should find an alternative method of doing what I'd like to do?</p>
