I read this great blog article Android Architecture Tutorial: Developing an App with a Background Service (using IPC)
The author show a tweet retrieving service running within a fixed interval in a separate process.
The service will keep running infinity. I realize to stop the process, going to Manage App and stop the service explicitly is the only way.
Note, this is not a very battery friendly way. Even the author claims himself.
Yes, there is a dark side to Android background services too – too
many services doing too much stuff in the background will slow down
the phone and suck the battery. However it’s not quite what I wanted
to bring up in this post, so maybe we’ll come back to resource
management etiquette in yet another post.
However, the author no longer update his blog.
I try to stop the service through TweetViewActivity.
@Override
protected void onDestroy() {
super.onDestroy();
try {
api.removeListener(collectorListener);
unbindService(serviceConnection);
} catch (Throwable t) {
// catch any issues, typical for destroy routines
// even if we failed to destroy something, we need to continue destroying
Log.w(TAG, "Failed to unbind from the service", t);
}
// New code added by Cheok. Not working. Not sure why.
this.stopService(intent);
Log.i(TAG, "Activity destroyed");
}
But that doesn’t work. I can see the service still running. May I know, what is the correct way to stop the IPC service, once I quit the Activity? What is a good battery saving strategy for the above example?
the reason it’s still running is because the system never called onDestroy.
if you check this link: http://developer.android.com/reference/android/app/Activity.html you can see from the graph that the onDestroy is only called when the system is about to clear your application from the memory, and depending on the memory constrain it might never be called at all.
The only callback that is guarantee to be called is
onPause()and that’s the one you should rely on to stop your service.