chromicant
chromicant

Reputation: 103

Stopping a foreground service on Android when the application crashes

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):

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

@Override
public void onDestroy() {
    stop();
}

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

 @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));
         }
     }
 }

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

Upvotes: 0

Views: 1381

Answers (1)

David Guo
David Guo

Reputation: 1759

Perhaps you can add a hook for your application's main thread(UI thread) for crash, see below:

Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
                //Kill the service.
            }
        });
    throw new RuntimeException("Uncaught Exception");

Upvotes: 1

Related Questions