Lessons learned : Stopping an android service

Scenario: An android service is running in the background quietly doing it’s thing.  When the application is closed, then the service should be stopped to conserve battery life and avoid nasty crashes due to null pointers. Simple right? In the onDestroy() callback of the application, call the stopService() method with the appropriate intent. Did that but the service refuses to die….the android service wouldn’t stop

Solution: In hindsight it was simple, and I should really learn to RTFM. But an important note to highlight when using android services:

A service will shut down after all bindService() calls have had their corresponding unbindService() calls. If there are no bound clients, then the service will also need stopService() if and only if somebody called startService() on the service [1]

In my case, apart from starting the service using startService(), I had also used bindService() to allow for other app components to check on the status of the service (running, or stopped). So the actual, proper onDestroy() call should look something like this:

@Override
protected void onDestroy() {

    Log.d("MainActivity", "onDestroy");
    this.mContext.unbindService(mConnection);
    Intent mServiceIntent = new Intent(mContext, MQTT_Service.class);
    mServiceIntent.setAction("ACTION_DESTROY");
    mContext.stopService(mServiceIntent);

 super.onDestroy();
}

Note the line:

this.mContext.unbindService(mConnection);

That made all the difference 🙂

References

[1] Android Developer, “Services”, http://developer.android.com/guide/components/services.html

Advertisement
Privacy Settings